简体   繁体   中英

ReactJS Can not get a Ref to a Class Component using ref callback

I'm trying to get a ref to a child component (Class component) from a parent component, I faced two issues:

Parent component

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

<Child ref={this.childRef} />

  1. The ref callback does not fire and get a null {current: null} in my reference.

  2. React-dev-tools warns me of passing ref from a functional component, but my child component is a class component..

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()?

Can anyone help ?

FYI This issue occurred while migrating my app from PReact to React. In Preact, the ref used to pass correctly:

Parent

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

You have to Forward Ref.

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

The ref is not passed from functional component to it's DOM element automatically. So you have to pass it manually. More about it https://reactjs.org/docs/forwarding-refs.html

Wrap it inside div. Try This:

 Parent component private childRef: RefObject<any> = React.createRef(); <div ref={this.childRef} > <Child /> <div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM