2016-10-05 111 views
0

我是新来做出反应,我正在做的是循环显示每个元素形式的道具,我想形成道具的图片组件更新,我尝试找到一种方法来做但我不知道该怎么做。 代码回路是这样的:反应循环更新状态

const pictureItems = this.props.imgFiles.map((img, index) => { 
     return <picture key={index} imgFile={img} pictureDataUpdate={this.onUpdatPicture} />; 
}); 

是我怎么可以更新都一直通到画面组件道具的问题? (我已经将图片信息传递给正在循环的组件)。我到目前为止这。

onUpdatPicture(data) { 
    console.log(data); 
    // this.setState(data); 
} 
+0

的画面组件应该调用在父组件,其然后更新的状态的功能。当状态更新时,它会重新渲染子组件并将新状态传递给它是道具 – erichardson30

回答

2

操纵发送给子组件的道具的最简单方法是将数据存储在父组件的状态中。这样做将允许您操作数据并将更新后的版本发送给您的子组件。

假设我们的父组件被作为图像道具发送一个图像url数组,我们需要在我们的代码中有两个主要部分:我们的孩子的更新函数来调用并映射我们的图像并创建我们的孩子。

class Gallery extends React.Component { 

    constructor(props) { 

     super(props) 

     //Setting our props to the state of the parent allows us to manipulate the data before sending it back to our child. 

     this.state = { 
      images: this.props.images || [] 
     } 

    } 

    update = (key, value) => { 

     // Our update function is sent the {key} of our image to update, and the new {value} we want this key to hold. 

     // After we are passed our data, we can simply map over our array and return the new array to our state. 

     this.setState({ 
      images: this.state.images.map((img, i) => i === key ? value : img) 
     }) 

    }; 

    render() { 

     return (

      <div className="gallery"> // Since we are going to have multiple children, we need to have a wrapper div so we don't get errors. 

       { 

        // We map over our data and send our child the needed props. 

        // We send our child the {src} of our image, our {update} function, the id our child will use to update our parent, and a key for React to keep track of our child components 

        images.map((img, i) => <Picture src={img} update={this.update} id={i} key={'picture_' + i} />) 

       } 

      </div> 

     ) 

    } 

} 

我们有更新的功能设置,我们的母公司是在我们的图像,以创建子组件映射后,所有剩下要做的就是建立我们的子组件来处理我们的数据。

class Picture extends React.Component { 

    render() { 

     return (

      // Notice our onClick is an arrow function that calls our update method. This is so we only call our update function once the onClick is fired, not when the component is being rendered. 

      <div className="picture" onClick={() => this.props.update(this.props.id, 'https://static.pexels.com/photos/189463/pexels-photo-189463.png')}> 

       <img src={this.props.src} /> 

      </div> 

     ) 

    } 

} 

鉴于上面的代码中,一旦我们使我们的画廊组件,随时随地的图像被点击时,孩子的形象被替换为新的图像。

Here is a link to a working example on CodePen.

+0

兰斯,很好的解释,真的很喜欢它。 –