admin管理员组

文章数量:1406951

I have a ponent 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>
  )
}

I have a ponent 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>
  )
}
Share edited Dec 27, 2019 at 21:30 norbitrial 15.2k10 gold badges39 silver badges64 bronze badges asked Dec 27, 2019 at 21:16 BlackbonnyBlackbonny 893 silver badges10 bronze badges 1
  • This is not reproducible, the value of inputRef is always going to be null in the code you have provided, you give the ref the value of null... – Brian Ogden Commented Dec 27, 2019 at 21:24
Add a ment  | 

1 Answer 1

Reset to default 7

Once you have the ref in the parent ponent 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 ponent to one of its children. This is typically not necessary for most ponents in the application.

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

const childDivRef = useRef(null);

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

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

import React, { forwardRef } from 'react';

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

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

I hope this helps!

本文标签: javascriptWhy is ref always nullStack Overflow