2017-03-22 91 views
0

假設我有一個父組件和一個子組件,它們都具有通用'item'中的值。
我如何同步Parent和Child狀態中的'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進行集中式存儲和派發具有新值的事件。那可行 –