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
1 Answer
Reset to default 7Once 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
版权声明:本文标题:javascript - Why is ref always null? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744953930a2634244.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论