2017-03-22 8 views
0

親アイテムと子コンポーネントの両方に共通の 'item'の値を持つ状態があるとします。
親と子の状態の 'item'値をどのように同期させるのですか?

より具体的には、親はアプリケーションのページであり、子供は個人化された入力である可能性があります。私が入力に書き込むときは、ページの状態を更新したいし、ページの状態が外部の要因(通知など)によって更新されたとき、私は入力を更新したい。React Native親子状態を同期する

export default class Parent extends Component { 

    constructor(props) { 
    super(props); 
    this.state={ 
     item: 1, 
    } 
    } 

    render() { 
    return (
     <Child 
     item = this.state.item 
     /> 
    ) 
    } 

    // I want any function of this type to automatically update 
    // child state (and redraw child) without having to manually resynchronise 
    modifyItem() { 
    this.setState({ item: neValue }) 
    } 

} 

export default class Child extends Component { 

    constructor(props) { 
    super(props); 
    this.state={ 
     item: this.props.item, 
    } 
    } 

    // I want any function of this type to automatically update 
    // parent state without having to manually resynchronise 
    modifyItem() { 
    this.setState({ item: neValue }) 
    } 

} 

答えて

0
export default class Parent extends Component { 

    constructor(props) { 
    super(props); 
    this.state={ 
     item: 1, 
    } 
    } 
    onItemChange(item) { 
    this.setState({ item }); 
    } 

    render() { 
    return (
     <Child 
     item = this.state.item 
     onItemChange={this.onItemChange.bind(this)} 
     /> 
    ) 
    } 

    // I want any function of this type to automatically update 
    // child state (and redraw child) without having to manually resynchronise 
    modifyItem() { 
    this.setState({ item: neValue }) 
    } 

} 

export default class Child extends Component { 

    constructor(props) { 
    super(props); 
    this.state={ 
     item: this.props.item, 
    } 
    } 

    // I want any function of this type to automatically update 
    // parent state without having to manually resynchronise 
    modifyItem() { 
    this.setState({ item: newValue }) 
    if (this.props.onItemChange) { 
     this.props.onItemChange(newValue); 
    } 
    } 

} 
+0

あなたの答えのおかげでそれがここには、自動同期はありませんマニュアルトリックです。私は私が何を探しているのかわからないが、それは私が探していた答えではない。 – alexandre

+0

ReduxまたはMobxを使用して、新しいストアド・イベントとディスパッチ・イベントを新しい値で使用してみてください。それは動作します –

関連する問題