【问题标题】:React forwardRef: ref and other propsReact forwardRef: ref 和其他 props
【发布时间】:2021-01-07 14:05:20
【问题描述】:

父组件:

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,我可以从props获得这些道具(onClickprop1prop2)。

这就是我需要做的吗?通过将ref 作为传递给孩子的最后一个道具?

如果Child 中有多个按钮需要ref,该怎么办?

【问题讨论】:

  • Props 将收到您在父组件中放置在子组件上的多个值,请按照第一条评论 :)

标签: javascript reactjs use-ref react-forwardref


【解决方案1】:
// in parent
<Child onClick={...} prop1={...} prop2={...} ref={ref} />

顺序无关紧要。 forwardRef 从属性中提取 ref 属性并创建一个包装器。

props 中提供了其他道具(forwardRef 回调函数中的第一个参数)

如果你想使用多个引用,你可以使用示例here

【讨论】:

    【解决方案2】:

    嗯,我已经采用了这种方法,

    父组件

    const Parent = (props) => {
      const ref = useRef();
    
      return <Child _ref={ref} />
    }
    

    子组件

    const Child = forwardRef(({ _ref, prop1, prop2, prop3, ...props }) => {
      return <button ref={_ref} ...>click</button>
    })
    

    成功了

    【讨论】:

      猜你喜欢
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 2020-04-24
      • 1970-01-01
      • 2019-10-16
      • 1970-01-01
      • 2022-01-06
      相关资源
      最近更新 更多