首页 > 解决方案 > 在反应中将值传递给子组件(this.props.children)

问题描述

我在 Layout 中有一个子组件,我也想传递一个 props 值。但我不知道怎么做。在下面的类中,layoutFileDataRequest() 在单击事件时从子组件接收字符串变量。需要将该值发送到 this.props.children 组件之一,以便它可以更新。

我该怎么做呢?在下面的代码中 React.cloneElement(child, {,它始终保持不变,这意味着我无法更新 child 道具。

  export default class Layout extends React.Component {
    constructor(props) {
      super(props)

      this.layoutFileDataRequest = this.layoutFileDataRequest.bind(this);
      this.state = {
        newData: '',
        returnData: 'test',

      }
    }

    /**
     *  Received request from server add it to 
     *  react component so that it can be rendered
     */
    layoutFileDataRequest(data) {
      this.setState({ returnData:data })
    }


    renderChildren() {
      return React.Children.map(this.props.children, child => {
        console.log(this.state.returnData); 
          return React.cloneElement(child, {
            data: this.state.returnData
          })
      });
    } 

    /**
     *  Render request
     * 
     * 
     */
    render() {
      const { location } = this.props;
      const title = this.state.newData;
      return (
        <div id="app-container" class={title}>
          <Nav location={location} />
          <main id="main">
            <h1>{title}</h1>
            <section>
                {this.renderChildren()}
            </section>
          </main>
          <Project layoutFileDataRequest={this.layoutFileDataRequest} />
          <Footer />
        </div>
      );
    }
  }


export default class Project extends React.Component {
  constructor(props) {
    super(props)

    this.projectFileDataRequest = this.projectFileDataRequest.bind(this);

    this.state = {
      newData: [],
    }

  }


  /**
   *  Received request from server add it to 
   *  react component so that it can be rendered
   */
  projectFileDataRequest(data) {
    this.props.layoutFileDataRequest(data);
  }


  /**
   *  Received request from server add it to 
   *  react component so that it can be rendered
   */
  componentDidMount() {
    ApiCalls.readSassDirData()
      .then(function (serverData) {
        this.setState({ newData: serverData[0].data })
      }.bind(this));
  }


  /**
   *  Render request
   */
  render() {
    const listOfObjects = this.state.newData;
    return (
      <aside id="project">
        <h2>Files</h2>
        <FileListing listOfObjects={listOfObjects} projectFileDataRequest={this.projectFileDataRequest} />,
       </aside>
    );
  }
}

标签: javascriptreactjs

解决方案


我认为错误出在 renderChildren 函数中。

代码

 renderChildren() {
      return React.Children.map(this.props.children, child => {
        console.log(this.state.returnData); 
          return React.cloneElement(child, {
            data: this.state.returnData
          })
      });
    }

新代码

renderChildren(){
    return this.props.children.map(child => 
        React.cloneElement(child, { 
            data: {...this.state.returnData }
        })
    );
}

推荐阅读