【问题标题】:How make child components of a child component have refs that the first-level child can use?如何使子组件的子组件具有一级子可以使用的引用?
【发布时间】:2016-11-22 21:34:30
【问题描述】:

如果我有以下 JSX,Childrefs 为空:

<Parent>
    <Child ref="first">
        <GrandChild ref="parentSeesThisNotChild" />
    </Child>
</Parent>

我希望Child 组件在其refs 中获得GrandChild。我该怎么做?

【问题讨论】:

    标签: javascript reactjs react-jsx jsx


    【解决方案1】:

    您必须修改Child 组件代码:

    const Child = React.createClass({
      render() {
        const childrenWithProps = React.Children.map(this.props.children, (child) => {
          return React.cloneElement(child, {
            ref: child.ref,
          });
        });
    
        return (
          <div>
            <h1>Child</h1>
            {childrenWithProps}
          </div>
        )
      },
    });
    

    【讨论】:

      猜你喜欢
      • 2020-04-03
      • 2021-07-30
      • 2014-07-02
      • 2022-11-26
      • 2020-06-25
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多