React forwardRef: ref 和其他道具
React forwardRef: ref and other props
一个parent组件:
const Parent = (props) => {
const ref = useRef();
return <Child ref={ref} />
}
和 child:
const Child = forwardRef((props, ref) => {
return <button ref={ref} ...>click</button>
})
如果我想向 Child
传递更多道具而不只是 ref
怎么办?
我搜索了文档和教程,但一无所获; trial-and-error,我猜这会起作用:
// in parent
<Child onClick={...} prop1={...} prop2={...} ref={ref} />
然后在Child
,我可以从props
.
得到这些道具(onClick
,prop1
,prop2
)
这就是我需要做的吗?通过将 ref
作为传递给 child?
的最后一个道具
如果我在 Child
中有多个按钮需要 ref
怎么办?
// in parent
<Child onClick={...} prop1={...} prop2={...} ref={ref} />
顺序无关紧要。 forwardRef
从属性中提取 ref 属性并创建一个包装器。
其他道具在props
中可用(forwardRef
中的第一个参数callback-function)
如果你想使用多个引用,你可以使用示例 。
好吧,我遵循了这种方法,
父组件
const Parent = (props) => {
const ref = useRef();
return <Child _ref={ref} />
}
子组件
const Child = forwardRef(({ _ref, prop1, prop2, prop3, ...props }) => {
return <button ref={_ref} ...>click</button>
})
成功了
一个parent组件:
const Parent = (props) => {
const ref = useRef();
return <Child ref={ref} />
}
和 child:
const Child = forwardRef((props, ref) => {
return <button ref={ref} ...>click</button>
})
如果我想向 Child
传递更多道具而不只是 ref
怎么办?
我搜索了文档和教程,但一无所获; trial-and-error,我猜这会起作用:
// in parent
<Child onClick={...} prop1={...} prop2={...} ref={ref} />
然后在Child
,我可以从props
.
onClick
,prop1
,prop2
)
这就是我需要做的吗?通过将 ref
作为传递给 child?
如果我在 Child
中有多个按钮需要 ref
怎么办?
// in parent
<Child onClick={...} prop1={...} prop2={...} ref={ref} />
顺序无关紧要。 forwardRef
从属性中提取 ref 属性并创建一个包装器。
其他道具在props
中可用(forwardRef
中的第一个参数callback-function)
如果你想使用多个引用,你可以使用示例
好吧,我遵循了这种方法,
父组件
const Parent = (props) => {
const ref = useRef();
return <Child _ref={ref} />
}
子组件
const Child = forwardRef(({ _ref, prop1, prop2, prop3, ...props }) => {
return <button ref={_ref} ...>click</button>
})
成功了