如何让组件的 ref 低 3 个级别?

问题描述

我使用 <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>
        )
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...