Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data between child and parent in react-native?

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

I just write an app with react-native and do not know how to update the parent state from the child element. thank you in advance

like image 835
user6094105 Avatar asked Jan 13 '17 15:01

user6094105


1 Answers

You need to pass from parent to child callback function, and then call it in the child.

For example:

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>
    );
  }
}
like image 166
Piotr Białek Avatar answered Sep 23 '22 08:09

Piotr Białek