2017-03-22 1 views
0

부모 항목과 공통 항목 '공통'항목에 값이있는 하위 구성 요소가 있다고 가정 해보십시오.
부모와 자식 상태에서 '항목'값을 어떻게 동기화합니까?

좀 더 구체적으로 말하자면, 부모는 앱의 페이지 일 수 있고 자식은 개인 입력 일 수 있습니다. 내가 입력에 쓸 때 페이지 상태를 업데이 트해야하고 페이지 상태가 외부 요소 (예 : 알림)에 의해 업데이 트됩니다 입력을 업데이 트해야합니다.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를 사용하여 중앙 집중식 상점 및 새로운 값으로 이벤트를 보내보십시오. 그게 효과가있다. –