【问题标题】:how can put ref to props.children如何将 ref 放入 props.children
【发布时间】:2020-04-30 20:01:21
【问题描述】:

我想要包装模块以供多用途。

所以,我制作了一个 ItemComponent

export const DragItem = (props: DragProps) => {
  const [{... }, fooRef] = useFoo({

  })

  return (
    props.children // how can i send fooRef to here??
  )
}

我应该将 ref 发送给 props.children 有可能吗?

【问题讨论】:

标签: reactjs typescript react-hooks ref


【解决方案1】:

检查这个:https://codesandbox.io/s/gracious-williams-ywv9m 您需要使用React.cloneElement 将额外数据附加/传递给孩子

export const DragItem = (props: DragProps) => {
  const [foo, fooRef] = React.useState({});
  var childrenWithRef = React.Children.map(props.children, function(child) {
    return React.cloneElement(child, { fooRef: fooRef });
  });
  return childrenWithRef;
};

【讨论】:

    【解决方案2】:

    我明白了。

    export const DragItem = (props: DragProps) => {
      const [{... }, fooRef] = useFoo({
    
      })
    
      return (
        React.cloneElement(props.children, { ref: fooRef })
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-18
      • 2021-02-14
      • 1970-01-01
      • 2020-05-27
      • 2020-11-20
      • 2020-10-22
      • 1970-01-01
      • 2018-07-15
      相关资源
      最近更新 更多