反应循环更新状态

时间:2016-10-05 18:34:06

标签: javascript reactjs state

我是新的反应和我正在做的是循环来显示每个元素形成道具我想要形成图片组件更新道具,我试图找到一种方法来做它但我不知道该怎么做。 循环代码如下:

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);
 }

1 个答案:

答案 0 :(得分:2)

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

假设我们的父组件被发送一个图像网址数组作为图像道具,我们在代码中需要两个主要部分:我们的孩子的更新功能可以调用和映射我们的图像并创建我们的孩子

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.