javascript - 如何在 React 中将 ref 向下传递多个级别?
问题描述
我可以通过以下方式将<Parent />
ref传递<Children />
给forwardRef
:
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 />
但是当我向ref添加一个级别时,返回总是未定义的。
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 作为道具名称而不是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>
)
}
推荐阅读
- vue.js - 自定义组件模糊
- reactjs - 用 props 反应传递的组件并装饰它
- multipart - fastify-multipart 崩溃服务
- azure-functions - 为什么建议禁用健康检查?
- c - 将伪代码转换为 C/C++ 源代码
- firebase - 如何将 Firebase 工具用于非 Google Workspace 的工作邮件
- python - 在 Pandas 中转置数据,行变成列
- javascript - Javascript Promise.all() 没有解决或拒绝
- docker - 当 docker 容器使用主机挂载的卷启动时,磁盘 I/O 是多少?如何减少它?
- express - 即使邮递员正在为同一个端点工作,Axios 也会抛出连接错误