简体   繁体   中英

Getting ref to props.children by React.cloneElement returns always null

I am trying to get child ref in Wrapper component but it always returns null. I use the common code:

export const SelectableItem = ({ children }: Props) => {
    const ref = useRef<HTMLElement>(null);

    useEffect(() => {
        setTimeout(() => console.log(ref?.current), 1000); // returns null
    }, []);

    const child = React.Children.only(children);

    return React.cloneElement(child, { ref: (r) => (ref.current = r) });

};
<SelectableItem>
   <SomeChild />
</SelectableItem>

What is wrong?

I am not getting that issue. The only thing I really changed was the console.log since it was producing an error. Hopefully you are able to figure out what was happening from the working code below.

 const SelectableItem = ({ children }: Props) => { const ref = React.useRef(null); React.useEffect(() => { setTimeout(() => { console.log(ref) }, 1000); }, []); const child = React.Children.only(children); return React.cloneElement(child, { ref: (r) => (ref.current = r) }); }; ReactDOM.render( <React.StrictMode> <SelectableItem> <div /> </SelectableItem> </React.StrictMode>, document.querySelector('.react') );
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></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