React-native - Passing data from one screen to another

£可爱£侵袭症+ 提交于 2019-11-30 09:11:29

So the problem seems to lie here:

<Navigator
  initialRoute={{ name: 'index', component: ContactList }}
  renderScene={(route, navigator) => {
    if (route.component) {
      return React.createElement(route.component, { navigator });
    }

    return undefined;
  }}
/>

In the renderScene function, you do receive the route (and use route.component) but you don't pass your route.props or route.passProps or what ever you want to call it! And from what I see in the source of Navigator at that moment you should have the full route object as you created it. So you should be able to pass your props along.

For example:

<Navigator
  initialRoute={{ name: 'index', component: ContactList }}
  renderScene={(route, navigator) => {
    if (route.component) {
      return React.createElement(route.component, { navigator, ...route.props });
    }

    return undefined;
  }}
/>

// push
<TouchableHighlight
  onPress={() => {
    this.props.navigator.push({
      component: ContactDetails,
      props: { /* ... */ }
    });
  }}
>

You could also setup redux, but that's not a requirement. Though if your app gets bigger you should really consider using an external store!


Update:

There is also another problem.

You use a functional components. Functional components don't have a this. They receive the props in parameter.

So it should be like this:

export default function ContactDetails(props) {
  return (
    <View style={styles.container}>
      <Text>{props.title}</Text>
      <Text>{props.first}</Text>
      <Text>{props.last}</Text>
    </View>
  );
}

I still feel the default navigation is to cumbersome. I highly suggest using this library for routing: https://github.com/aksonov/react-native-router-flux

Replace code :

<TouchableOpacity
      onPress={() => this._handlePress()}
      style={styles.button}
>

With :

<TouchableOpacity
      onPress={() => this._handlePress()}
      style={styles.button}
     navigator={navigator} {...route.props}
>

This is fine:

this.props.navigator.push({
component: ContactDetails,
   props: {
    title: rowData.name.title,
    first: rowData.name.first,
    last: rowData.name.last,
  }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!