2017-03-22 97 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进行集中式存储和派发具有新值的事件。那可行 –