ReactJS无法使用ref回调获取对类组件的引用

问题描述

我试图从父组件获取对子组件(类组件)的引用,我遇到两个问题:

Parent component

private childRef: RefObject<any> = React.createRef();

<Child ref={this.childRef} />

  1. 引用回调不会触发,并且在我的引用中得到空{current: null}

  2. React-dev-tools警告我从功能组件传递ref,但我的子组件是类组件。

react_devtools_backend.js:2273 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

任何人都可以帮忙吗?

仅供参考,将我的应用程序从PReact迁移到React时发生此问题。 在Preact中,裁判常用于正确传递:

父母

 <Child ref={(ref: any) => {
                      if (ref && ref._component) {
                        this.childRef = ref._component._component
                      }
                    }}
</Child>

解决方法

您必须转发参考

const Child = React.forwardRef((props,ref) => (
  <div ref={ref} >
    ....
  </div>
))

引用不会自动从功能组件传递到其DOM元素。因此,您必须手动传递它。进一步了解https://reactjs.org/docs/forwarding-refs.html

,

将其包装在div中。试试这个:

Parent component

private childRef: RefObject<any> = React.createRef();

<div ref={this.childRef} >
<Child />
<div>