2016-08-15 39 views
0

私はブール状態のプロパティ "showModal"を持つ親コンポーネントを持っています。 showModalがtrueの場合、子コンポーネント「Modal」をレンダリングします。このモーダルには、 "showModal"プロパティをfalseに戻すための閉じるボタンがあります。 "showModal"は子のModalコンポーネントに小道具として渡されますが、小道具はReactで不変なので、私はそれを変更するための正しいパターンを見つけていません。親コンポーネントの状態を子コンポーネントから変更するにはどうすればよいですか?

私はタップすることができますいくつかの種類の双方向データバインディングはありますか?これに対処する最善の方法は何ですか?

答えて

3

ここであなたがそれを行うことができる方法です。そして、ここで働く例JSBinです:https://jsbin.com/yixano/2/edit?html,js,output

var ModalParent = React.createClass({ 
    getInitialState: function() { 
    return {showModal: false}; 
    }, 

    toggleShowModal: function() { 
    this.setState({showModal: !this.state.showModal}); 
    }, 

    render: function() { 
    return (
     <div> 
     <button type="button" onClick={this.toggleShowModal.bind(this)}>Toggle Show Modal</button> 
     {this.state.showModal ? 
      <Modal onModalClose={this.toggleShowModal.bind(this)}/> : 
      <div></div>} 
     <h4>State is: </h4> 
     <pre>{JSON.stringify(this.state, null, 2)}</pre> 
     </div>); 
    } 
}); 

var Modal = React.createClass({ 
    render: function(){ 
    return <div><button type="buton" onClick={this.props.onModalClose}>Close</button></div> 
    } 
}); 

ReactDOM.render(<ModalParent/>, document.getElementById("app")); 

は、ここでの考え方は、親の中で状態は子供のアクションに基づいて変更することができるようにモーダルにModalParent上の関数への参照を渡すことです。

ご覧のとおり、子供には "onModalClose"という小道具があり、閉じるボタンをクリックすると呼び出される関数リファレンスが必要です。親では、対応するtoggleShowModalをこのonModalCloseプロパティにバインドします。

+0

これは私が探していた答えです。ありがとうございました! –

2

親コンポーネントでshowModalの状態を更新し、それをコールバックとしてpropsの子コンポーネントに渡すメソッドを作成できます。 propsに渡された関数を実行する子コンポーネントの関数を定義します。モデルを閉じる 'x'にonClickリスナーを設定すると、子関数が呼び出され、親にある関数が実行されます。これにより、親の状態が更新され、両方が再レンダリングされます。

class MyParent extends Component { 
    toggleShowModal(){ 
    this.setState({showModal: !this.state.showModal}) 
    } 

    render(){ 
    return (
    <Modal toggleShowModalCallback={this.toggleShowModal.bind(this)} /> 
    ) 
    } 

}

class Modal extends Component { 

    updateParent(){ 
    this.props.toggleShowModalCallback() 
    } 

    render(){ 
    return(
    <CloseModalButton onClick={this.updateParent.bind(this)} /> 
    ) 
    } 
} 
+0

Modalクラスに対してupdateParentメソッドは必要ありません。 this.props.toggleShowModalCallbackを使用することができます。以下の答えを見てください。 – KumarM

関連する問題