如何在 React 中将 ref 向下传递不止一个级别?
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 />
添加一个级别时,引用 returns 始终未定义。
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 来做到这一点并避免道具钻探,但对于这个特定示例,我宁愿选择道具钻探。有什么提示吗?
您的一个选择是将 ref 作为 prop 名称而不是 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>
)
}
我可以通过 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 />
添加一个级别时,引用 returns 始终未定义。
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 来做到这一点并避免道具钻探,但对于这个特定示例,我宁愿选择道具钻探。有什么提示吗?
您的一个选择是将 ref 作为 prop 名称而不是 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>
)
}