父组件:const Parent = (props) => { const ref = useRef(); return <Child ref={ref} />}和孩子:const Child = forwardRef((props, ref) => { return <button ref={ref} ...>click</button>})如果我想传递更多的道具怎么Child办ref?我搜索了文档和教程,但一无所获;通过反复试验,我想这会起作用:// in parent<Child onClick={...} prop1={...} prop2={...} ref={ref} />然后在 中,Child我可以从 中获取这些道具 ( onClick,, ) 。prop1prop2props这就是我需要做的吗?通过把ref作为最后一个道具传递给孩子?如果我有多个按钮Child需要一个怎么办ref?
2 回答
万千封印
TA贡献1891条经验 获得超3个赞
// in parent <Child onClick={...} prop1={...} prop2={...} ref={ref} />
顺序无关紧要。forwardRef
从属性中提取 ref 属性并创建一个包装器。
其他道具可用(回调函数props
中的第一个参数)forwardRef
汪汪一只猫
TA贡献1898条经验 获得超8个赞
好吧,我遵循了这种方法,
父组件
const Parent = (props) => {
const ref = useRef();
return <Child _ref={ref} />
}
子组件
const Child = forwardRef(({ _ref, prop1, prop2, prop3, ...props }) => {
return <button ref={_ref} ...>click</button>
})
它奏效了
添加回答
举报
0/150
提交
取消