2017-01-13 1 views
1
module.exports= class APP extends React.Component { 
    constructor(props){ 
    super(props); 
    this.state = { 
     key1:'key1', 
     key2:'key2' 
    }; 
    render() { 
    return (
     <View> 
      <Button 
      onPress={this.goToTisch}> 
      1 
      </Button> 
      <Button 
      onPress={this.goToTisch}> 
      2 
      </Button> 
     </View> 
    ); 
    } 
} 

나는 단지 react-native로 응용 프로그램을 작성하고 자식 요소에서 부모 상태를 업데이트하는 방법을 모릅니다. 사전에 감사합니다react-native에서 자식과 부모간에 데이터를 전달하는 방법은 무엇입니까?

답변

7

부모 콜백 콜백 함수에서 자식 콜백 함수로 전달한 다음 하위 콜백 함수를 호출해야합니다. 예를 들어

:

class Parent extends React.Component { 
    constructor(props){ 
    super(props); 
    this.state = { 
     show: false 
    }; 
    } 
    updateState =() => { 
     this.setState({ 
      show: !this.state.show 
     }); 
    } 
    render() { 
    return (
     <Child updateState={this.updateState} /> 
    ); 
    } 
} 

class Child extends React.Component { 
    handleClick =() => { 
     this.props.updateState(); 
    } 
    render() { 
    return (
     <button onClick={this.handleClick}>Test</button> 
    ); 
    } 
} 
+0

감사합니다! 나는 그것을 검사했다. – user6094105

+0

이 작업을 수행 할 때 "기존 상태 전환 중에 업데이트 할 수 없습니다"라는 메시지가 나타납니다. – Hugo

0

사용 소품 :

부모 :

<Parent> 
    <Child onChange={this.change} /> 
</Parent> 

아이 : 당신이 당신의 부모에 원하는대로 그냥 할 수있는이와

<button onclick={this.props.onChange('It Changed')} /> 

.

관련 문제