简体   繁体   中英

How to pass all state values to number of child components and update the parent

I am new to react native and I have some challenge in my first app. In my app I have parent component and more then one child component, in parent component I have state with values that I need to pass to all of my child components, in every child component if the state was update I need the parent gets update too, but I struggle how to pass all state values to child components.

In my parent component (NavigatorRiddles) I am using navigator, my child components are HomeScreen and Riddles:

export default class NavigatorRiddles extends React.Component {
  constructor(props) {
    super(props);
    this.state = { userAnswer: '', count: 0, diamonds: 0, urldatabase: {}, wordsnumber: 0, riddleletter: '' };
  }

  render() {
    return (
      <View>
        <HomeScreen getState={...this.state}/>
      </View>
    )
  }
}

class RiddlesScreen extends React.Component {
  static navigationOptions = {
    header: null
  }
  render() {
    return (
      <View>
        <Riddles navigation={this.props.navigation} getState={...this.state}/>
      </View>
    )
  }
}

const Navigate = StackNavigator(
  {
    Home: { screen: HomeScreen },
    Riddles: { screen: RiddlesScreen },
  },

)

In the child components I don't new how to make the component actually to get that state

every help really appreciated! thanks.

I'm not sure if I understand you correctly, but you could pass down your state like so:

<HomeScreen navigatorState={this.state} />

and then access this prop in the child:

class RiddlesScreen extends React.Component {
  static navigationOptions = {
    header: null
  }
  render() {
    console.log(this.props.navigatorState) // { userAnswer: '', count: 0, diamonds: 0, urldatabase: {}, wordsnumber: 0, riddleletter: '' }
    return (
      <View>
        <Riddles navigation={this.props.navigation} getState={...this.state}/>
      </View>
    )
  }
}

Let me know if you have any questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM