反应循环更新状态

react loop update state

我是 React 的新手,我正在做的是循环以显示道具中的每个元素,我想形成图片组件更新道具,我试图找到一种方法来做到这一点但是我不知道该怎么做。 循环代码是这样的:

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

处理发送到 child 组件的道具的最简单方法是将数据存储在 parent 组件的状态中。这样做将允许您操作数据并将更新版本发送到您的 child 组件。

假设我们的 parent 组件被发送了一个图像 url 数组作为 images 道具,我们的代码中需要两个主要部分:我们的 child 调用的更新函数和映射我们的图像并创建我们的 children.

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>

        )

    }

}

在我们设置了更新函数并且我们的 parent 正在映射我们的图像以创建 child 组件之后,剩下要做的就是设置我们的 child 组件来处理我们的数据。

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>

        )

    }

}

根据上面的代码,一旦我们渲染了图库组件,只要单击图像,child 的图像就会被替换为新图像。

Here is a link to a working example on CodePen.