gpt4 book ai didi

javascript - react forwardRef : ref and other props

转载 作者:行者123 更新时间:2023-12-05 03:49:23 27 4
gpt4 key购买 nike

父组件:

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 ( prop1prop2props ) .

这就是我需要做的吗?通过输入 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com