[英]How to pass a reference created by react hook of parent component to child components?
My Code:我的代码:
const MyComponent: React.FC = () => {
const ParentReference = useRef(null);
return(
<Parent className="d-flex flex-row" ref={ParentReference}>
<ChildComponent
className="mr-3"
target={ParentReference.current}
/>
<AnotherChild className="mr-3" />
</Nav>
)};
As seen in the code above, I have created a reference using useRef hook and attached it to my ParentComponent.如上面的代码所示,我使用 useRef 挂钩创建了一个引用并将其附加到我的 ParentComponent。 Now am passing to ChildComponent by means of target prop and using it to do some dom manipulation inside the child.
现在我通过 target 道具传递给 ChildComponent 并使用它在孩子内部进行一些 dom 操作。
Issue: I am getting ParentReference as null for the first render of the component.问题:对于组件的第一次渲染,我得到的ParentReference为null 。 (If I force re-render on change of the ParentReference it will update and re-render whole component then it will have value.)
(如果我在更改 ParentReference 时强制重新渲染,它将更新并重新渲染整个组件,然后它将有价值。)
How to get the ParentReference inside my child Component for initial render itself?如何在我的子组件中获取 ParentReference 以进行初始渲染?
segFault's reference to this answer is correct. segFault 对此答案的引用是正确的。 Your ref it not initialized until after your component's first render.
你的 ref 在你的组件第一次渲染之后才初始化。 So when you render your
<ChildComponent target={ParentReference.current} />
, the ref is not yet defined.因此,当您呈现
<ChildComponent target={ParentReference.current} />
时,ref 尚未定义。
In this scenario you might consider using a useEffect
to set a state variable on first render, and conditionally rendering the <ChildComponent />
once that state variable is set.在这种情况下,您可以考虑使用
useEffect
在第一次渲染时设置 state 变量,并在设置 state 变量后有条件地渲染<ChildComponent />
。
const MyComponent: React.FC = () => {
const ParentReference = useRef(null);
// define state variable defining the ref as not yet ready
const [refReady, setRefReady] = useState(false)
// On first mount, set the variable to true, as the ref is now available
useEffect( () => {
setRefReady(true)
}, [])
return(
<Parent className="d-flex flex-row" ref={ParentReference}>
{refReady && <ChildComponent
className="mr-3"
target={ParentReference.current}
/>}
<AnotherChild className="mr-3" />
</Nav>
)};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.