如何获得组件 3 级别的引用?

How to get a ref of a component 3 levels lower?

我和 <canvas> 一起工作,这就是我需要它的原因,我知道它通常会闻起来,但这种情况不会。

我有组件树:

<A>
  <B>
    <C>
     <D/>
    </C>
  </B>
</A>

只有这个被拆分成组件。

如何在 <A> 组件中获取 <D> 组件的引用?

类似于:

// 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里面的statements移动到一个函数中,作为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>
        )
    }
}