React - 通过 this.props.children 的状态

React - Passing State with this.props.children

所以我试图将一些道具从我的顶级组件传递到 child 组件,我在网上做了一些搜索,但找不到任何显示我如何传递 this.props.children WITH 一些值我的组件的状态。这是我的代码。

布局(Parent):

export default class Layout extends React.Component {
    constructor (props) {
    super(props)
    this.state = { data: 'test' }
  }

    render() {
        const {location} = this.props;
        console.log("layout");
        return (
            <div>
                <Nav location={location}/>
                <div className="container">
                    <div className="row">
                        <div className="col-lg-12">

                            {this.props.children}, data={this.state.data}

                        </div>
                    </div>
                    <Footer/>
                </div>
            </div>

        );
    }
}

当我在下一个组件中调用“数据”道具时:

主页 (Child):

//ON COMPONENT RENDER
    componentDidMount = () => {
        console.log("home");
        console.log(this.props.data);
    }

在我的控制台中 returns:

home

Undefined

关于我应该如何使用兴奋剂的任何指示?感谢您的帮助,提前致谢。

在布局组件中对 this.state.data 执行 console.log。我认为它也未定义。

我认为您需要在调用构造函数 super() 之前或在构造函数外部静态设置状态。

编辑:所以 this.props.children 是反应元素?你需要克隆它来传递不同的道具。

React.cloneElement(this.props.children, {
    name: props.name
})

如果您试图直接向子级添加道具,这将不会真正起作用,因为组件被认为是不可变的。相反,您应该做的是创建一个包含子项克隆的地图。

这个博客 post 解释得相当好:http://jaketrent.com/post/send-props-to-children-react/

以及为您的代码更改的相关代码片段:

class Layout extends React.Component {
  constructor (props) {
    super(props)
    this.state = { data: 'test' }
  }

  renderChildren() {
    return React.Children.map(this.props.children, child => {
      if (child.type === Child) {
        return React.cloneElement(child, {
          data: this.props.data
        })
      } else {
        return child
      }
    });
  }

  render() {
    const {location} = this.props;
    console.log("layout");
    return (
        <div>
            <Nav location={location}/>
            <div className="container">
                <div className="row">
                    <div className="col-lg-12">
                        {this.renderChildren()}
                    </div>
                </div>
                <Footer/>
            </div>
        </div>
    );
  }
}