将传递道具传递给另一个循环组件

时间:2018-10-26 18:21:58

标签: reactjs react-native

我正在尝试将循环组件的道具(使用array.map())传递给其他组件,如下所示:

{this.posts.map((item, index) => {
    return (
         <Post
          item={item} 
          key = {index}
         />
    );
  })
}

因此,呈现了许多“ Post”同级组件,但每个组件具有不同的项目(数据)和键。现在,我希望将一个特定Post组件的道具(在两个组件之间共享状态)发送给另一个特定的同级Post组件。也就是说,我希望选择一个特定的Post组件(也许具有键值?并且仅将状态发送给另一个特定的Post组件)。 我将如何实现?

谢谢。

1 个答案:

答案 0 :(得分:0)

我建议绑定一个将更新this.posts的函数。这样一来,您的组件将全部更新,而不必处于潜在的纠缠状态。

这个想法是函数updatePosts将采用目标索引(键)子组件进行更新并将新状态传递给它。在下面的代码中,如果触发了updatePosts({firstName:'Harry',lastName:'Styles'},1),则状态将从第一个元素“ Foo Bar”变为“ Harry Styles”,子组件将重新呈现。

import React from 'react';

class PostMaster extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      //the array you use to render child components will be managed in a state like this
      data: [
        {
          firstName: 'Foo',
          lastName: 'Bar'
        },
        {
          firstName: 'James',
          lastName: 'Bond'
        },
        {
          firstName: 'Harry',
          lastName: 'Potter'
        }
      ]
    };
    this.updatePosts = this.updatePosts.bind(this);
  };

  /**
   * stateData (object)     the data you want to go in a given index
   * index (int)            the child component you would like to update
  /
  updatePosts(stateData, index) {
    let newData = this.state.data;
    newData[index] = stateData;
    this.setState({data: newData});
    //you can always push instead of reassigning
  };

  render() {
    return(
      <div>
        {this.state.data((item, index) => {
            return (
                <Post
                  item={item} 
                  key={index}
                  update={this.updatePosts}
                />
            );
          })}
      </div>
    )
  }
}
相关问题