父组件:
const Parent = (props) => {
const ref = useRef();
return <Child ref={ref} />
}
和 child :
const Child = forwardRef((props, ref) => {
return <button ref={ref} ...>click</button>
})
如果我想传递更多的属性给 Child
怎么办?不仅仅是ref
?
我搜索了文档和教程,但一无所获;通过反复试验,我想这会奏效:
// in parent
<Child onClick={...} prop1={...} prop2={...} ref={ref} />
然后在Child
,我可以从 onClick
得到这些 Prop ( prop1
, prop2
, props
) .
这就是我需要做的吗?通过输入 ref
作为传递给 child 的最后一个 Prop ?
如果我在 Child
中有多个按钮怎么办?需要 ref
?
最佳答案
// in parent
<Child onClick={...} prop1={...} prop2={...} ref={ref} />
顺序无关紧要。 forwardRef
从属性中提取 ref 属性并创建一个包装器。
其他 Prop 在 props
中可用(forwardRef
回调函数中的第一个参数)
如果你想使用多个引用,你可以使用示例 here .
关于javascript - react forwardRef : ref and other props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63992924/