[英]How to pass a ref down more than one level in React?
我可以通過forwardRef
將<Parent />
引用傳遞給<Children />
:
const Children = forwardRef((
props, ref) => {
return <div ref={ref}>{props.children}</div>
})
export default function App() {
const ref = useRef()
console.log('ref', ref)
return (
<Children ref={ref}>I'm a child</Children>
);
}
但是,當我向<GrandChildren />
添加一個級別時,參考返回始終未定義。
const GrandChildren = forwardRef((props, ref) => {
return <div ref={ref}>{props.children}</div>
})
const Children = forwardRef((
props, ref) => {
return <div><GrandChildren ref={ref} /></div>
})
export default function App() {
const ref = useRef()
console.log('ref', ref)
return (
<Children ref={ref}>I'm a child</Children>
);
}
我知道我們可以使用 Context 執行此操作並避免道具鑽孔,但對於這個特定示例,我寧願 go 用於道具鑽孔。 任何提示?
您擁有的一種選擇是將 ref 作為道具名稱而不是ref
傳遞。 例如:
import { useRef, forwardRef } from "react"
const GrandChildren = forwardRef((props, ref) => {
return <div ref={ref}>{props.children}</div>
})
const Children = (props) => {
return (
<div>
{props.children}
<GrandChildren ref={props.grandchildenRef}>
I'm a grandchild
</GrandChildren>
</div>
)
}
export default function App() {
const ref = useRef()
const handleClick = () => {
console.log("ref", ref)
}
return (
<div onClick={handleClick}>
<Children grandchildenRef={ref}>I'm a child</Children>
</div>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.