2017-03-22 7 views
0

Angenommen, ich habe eine übergeordnete Komponente und eine untergeordnete Komponente, die beide über Status mit einem gemeinsamen Wert für 'item' verfügen.
Wie synchronisiere ich den 'Element'-Wert im Eltern- und Kind-Status?

Um konkreter zu sein, könnte der Elternteil eine Seite der App sein und das Kind könnte eine personalisierte Eingabe sein. Wenn ich in die Eingabe schreibe, möchte ich, dass der Seitenzustand aktualisiert wird, und wenn der Seitenzustand durch einen externen Faktor (beispielsweise durch eine Benachrichtigung) aktualisiert wird, möchte ich, dass die Eingabe aktualisiert wird.Native synchronisieren Eltern- und Kindstatus synchronisieren

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 }) 
    } 

} 

Antwort

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

Vielen Dank für Ihre Antwort, aber das ist ein manueller Trick gibt hier keine automatische Synchronisation ist. Ich weiß nicht, ob das, was ich suche, machbar ist, aber das ist nicht die Antwort, nach der ich gesucht habe. – alexandre

+0

Verwenden Sie Redux oder Mobx für zentralisiertes Speicher- und Versandereignis mit neuem Wert. Das wird funktionieren –