Pass state from child to parent component in React Native

筅森魡賤 提交于 2019-12-05 04:47:06

You can try redux, It store data in state by props whenever you change data in redux store.

Other idea is, pass a setState method to child component.

Parent

class Parent extends Component {
    updateState (data) {
        this.setState(data);
    }
    render() {
        <View>
            <Child updateParentState={this.updateState.bind(this)} />
        </View>
    }
}

Child

class Child extends Component {
    updateParentState(data) {
        this.props.updateParentState(data);
    }

    render() {
        <View>
            <Button title="Change" onPress={() => {this.updateParentState({name: 'test'})}} />
        </View>
    }
}

You should look into a state management module such as Redux to see if it would work with your app, but without anything you can achieve it by doing something like this:

// ---------------------------------------------
// Parent:

class Parent extends React.Component {
  updateData = (data) => {
    console.log(`This data isn't parent data. It's ${data}.`)
    // data should be 'child data' when the
    // Test button in the child component is clicked
  }
  render() {
    return (
      <Child updateData={val => this.updateData(val)} />
    );
  }
}

// ---------------------------------------------
// Child:

class Child extends React.Component {
  const passedData = 'child data'
  handleClick = () => {
    this.props.updateData(passedData);
  }
  render() {
    return (
      <button onClick={this.handleClick()}>Test</button>
    );
  }
}

After trying several different options, we decided to implement Redux to manage state in our app. This was difficult to do with our navigation, but now that everything is set up I'd say it was well worth the effort. There are other state management solutions like MobX we looked into, but decided to go with Redux because it fit with our navigation layout.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!