简体   繁体   中英

Why is ref always null?

I have a component below, at the first render I have the correct ref to input, but then I always get null , with the next render, please tell me why? ref is passed on through props to input:

const inputRef = useRef(null);
useEffect(() => {
  setTimeout(() => {
    if (inputRef.current) {
        inputRef.current.focus();
    }
  });
 }, [inputRef]);

render() {
  return(
    <div>
      <FirstComponent />
      {({ selectedItem, items }) => (
             <SecondCompontnt
                inputRef={inputRef}
                items={items}
                onSelect={onSelect}
                value={selectedItem}
              />
          )}
    </div>
  )
}

Once you have the ref in the parent component for one of its children then you need to apply so called Forwarding Ref technique , as the documentation states:

Ref forwarding is a technique for automatically passing a ref through a component to one of its children. This is typically not necessary for most components in the application.

Let's say you have in the parent component as the following:

const childDivRef = useRef(null);

return <>
  <ChildComponent ref={childDivRef} />
</>

Then you need to have in the child component as below:

import React, { forwardRef } from 'react';

const ChildComponent = forwardRef((props, ref) => {
    return <div ref={ref} className="child-component">
        <h3>Child component</h3>
    </div>
})

If you need a working example, please find this GitHub repository what I made earlier: https://github.com/norbitrial/react-forwarding-ref-example

I hope this helps!

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