哈士奇WWW
2023-03-18 11:20:03
父組件:const Parent = (props) => { const ref = useRef(); return <Child ref={ref} />}和孩子:const Child = forwardRef((props, ref) => { return <button ref={ref} ...>click</button>})如果我想傳遞更多的道具怎么Child辦ref?我搜索了文檔和教程,但一無(wú)所獲;通過(guò)反復(fù)試驗(yàn),我想這會(huì)起作用:// in parent<Child onClick={...} prop1={...} prop2={...} ref={ref} />然后在 中,Child我可以從 中獲取這些道具 ( onClick,, ) 。prop1prop2props這就是我需要做的嗎?通過(guò)把ref作為最后一個(gè)道具傳遞給孩子?如果我有多個(gè)按鈕Child需要一個(gè)怎么辦ref?
2 回答

萬(wàn)千封印
TA貢獻(xiàn)1891條經(jīng)驗(yàn) 獲得超3個(gè)贊
//?in?parent <Child?onClick={...}?prop1={...}?prop2={...}?ref={ref}?/>
順序無(wú)關(guān)緊要。forwardRef
從屬性中提取 ref 屬性并創(chuàng)建一個(gè)包裝器。
其他道具可用(回調(diào)函數(shù)props
中的第一個(gè)參數(shù))forwardRef

汪汪一只貓
TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
好吧,我遵循了這種方法,
父組件
const Parent = (props) => {
const ref = useRef();
return <Child _ref={ref} />
}
子組件
const Child = forwardRef(({ _ref, prop1, prop2, prop3, ...props }) => {
return <button ref={_ref} ...>click</button>
})
它奏效了
添加回答
舉報(bào)
0/150
提交
取消