问题描述
我使用 <canvas>
,这就是我需要它的原因,我知道它通常有气味,但不是这种情况。
我有组件树:
<A>
<B>
<C>
<D/>
</C>
</B>
</A>
仅将其拆分为组件。
如何在 <D>
组件中获取 <A>
组件的引用?
类似:
// i use class components,it just for example
class A extends React.Component {
refD = React.createRef<D>();
componentDidMount() {
// do something with refD
}
render() { return <B innerRef={innerRef} />; }
}
const B = ({ innerRef }) => <C innerRef={innerRef} />;
const C = ({ innerRef }) => <D ref={innerRef} />;
const D = () => <div>yep,i'm just div</div>;
我用过 forwardRef
,但它只在一级起作用
解决方法
你可以把A的componentDidMount
里面的语句移到一个函数中,作为props传给D。DOM变化后,你可以从D的componentDidMount
中调用这个函数
class A extends React.Component {
constructor(props) {
super(props)
}
dMounted(ref) {
// do something with D's ref
}
render() {
return(
<B dMounted={this.dMounted}/>
)
}
}
const B = (props) => <C {...props}/>
const C = (props) => <D {...props}/>
class D extends React.Component {
constructor(props) {
super(props)
this.ref = React.createRef()
}
componentDidMount() {
this.props.dMounted(this.ref)
}
render() {
return(
<div ref={this.ref}>yep,i'm just div</div>
)
}
}