React-native - Passing data from one screen to another

前端 未结 3 1334
灰色年华
灰色年华 2020-12-31 14:57

I am trying to learn how to use react-native, so I am putting up a small app that fetch a list of users from a server, displays it in a listview and where press

相关标签:
3条回答
  • 2020-12-31 15:50

    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>
      );
    }
    
    0 讨论(0)
  • 2020-12-31 16:00

    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,
      }
    });
    
    0 讨论(0)
  • 2020-12-31 16:02

    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

    0 讨论(0)
提交回复
热议问题