2016-10-05 6 views
0

私は反応するのが新しく、私がやっていることは、各要素のフォームを小道具に見せるためのループであり、私はその小道具の画像コンポーネントの更新をしたい、私はやり方を見つけようとしているしかし、私はそれをやる方法を知らなかった。 forループ コードはこれです:react loop update sate

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の配列が送られてきたとすると、私たちのコードには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.

+0

だったので、ランス、大きな説明は、本当にそれを楽しんだ。 –