【问题标题】:How do I pass values from a parent element to a child element in ReactJs?如何在 ReactJs 中将值从父元素传递给子元素?
【发布时间】:2015-07-28 15:42:22
【问题描述】:

如果我有嵌套的 react 元素,当子元素不在父元素内部时,如何将父元素中的值传递给子元素。

React.render(
  <MainLayout>
    <IndexDashboard />
  </MainLayout>,
  document.body);

在这段代码中,我希望能够在 IndexDashboard 元素中访问 MainLayout 元素中的一些函数。如何将这些函数传递给子元素?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    可以使用cloneElement函数修改子组件的props:

    #MainLayout
    
    render: function(){ (
      var contents = React.Children.map(this.props.children, function(child) {
        return React.cloneElement(child, {onSomeEvent: this.onSomeChildEvent})
      }.bind(this));
    
      return (
            <div>
                {contents}
            </div>
      );       
    }
    

    详情请参考以下链接:https://facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html

    【讨论】:

      【解决方案2】:

      您通常不会像在 React.render 调用中那样渲染子元素,而是将 IndexDashboard 移动到您的 MainLayout 组件的渲染中,以便您可以将所需的道具传递给它。

      根据您的评论进行编辑:在动态呈现子项的情况下,我建议根据您所在的页面将其作为道具传递。我不知道 JSX 是否支持这种语法,但你可以肯定地使用 React.createElement

      React.render(
        <MainLayout childProp={ IndexDashboard }/>,
      document.body);
      
      #MainLayout
      render: function(){ (
        return (
          React.createElement(this.props.childProp, [otherProps...])
        )       
      }
      

      我不确定你所说的“它不是父级内部的”是什么意思,因为它显然是用它渲染的。如果您绝对不能将子渲染函数移动到父渲染函数,您可能希望使用类似通量的架构,使用存储来容纳 MainLayoutIndexDashboard 都需要的数据

      【讨论】:

      • 问题是子组件只有一页的IndexDashboard,子组件在每一页上会有所不同,但是布局组件是一样的。
      猜你喜欢
      • 2014-11-14
      • 2021-11-10
      • 2019-11-09
      • 1970-01-01
      • 2022-12-24
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多