React forwardRef: ref 和其他道具

父组件:


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?


哈士奇WWW
浏览 94回答 2
2回答

万千封印

// in parent <Child onClick={...} prop1={...} prop2={...} ref={ref} />顺序无关紧要。forwardRef从属性中提取 ref 属性并创建一个包装器。其他道具可用(回调函数props中的第一个参数)forwardRef

汪汪一只猫

好吧,我遵循了这种方法,父组件const Parent = (props) => {&nbsp; const ref = useRef();&nbsp; return <Child _ref={ref} />}子组件const Child = forwardRef(({ _ref, prop1, prop2, prop3, ...props }) => {&nbsp; return <button ref={_ref} ...>click</button>})它奏效了
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript