Passing Data Using React-Native Navigation

后端 未结 7 2114
野性不改
野性不改 2020-12-16 13:30

Im trying to pass data between screens in my app. Currently I am using


\"react-native\": \"0.46.0\",
\"react-navigation\": \"^1.0.0-beta.11\"
<         


        
7条回答
  •  半阙折子戏
    2020-12-16 14:29

    All the other answers now seem outdated. In the current react navigation version, ("@react-navigation/native": "^5.0.8",), you first pass value between one screen from another like this:

           function HomeScreen({ navigation }) {
          return (
            
              Home Screen
              

    and then in the component you are redirecting, you get the data you passed like this:

    function DetailsScreen({ route, navigation }) {
      /* 2. Get the param */
      const { itemId } = route.params;
      const { otherParam } = route.params;
      return (
        
          Details Screen
          itemId: {JSON.stringify(itemId)}
          otherParam: {JSON.stringify(otherParam)}
        
      );
    }
    

    So, basically, the data now is inside this.props.route.params. In those examples above, I showed how to get them from functional components, but in class components is similar, I did something like this:

    First I passed the data from this ProfileButton, within it's handleNavigate function, like this:

    
    // these ProfileButton and ProfileButtonText, are a Button and a Text, respectively,
    // they were just styled with styled-components 
     this.handleNavigate(item) 
      
          check profile
      
    
    

    where the handleNavigate goes like this:

       handleNavigate = user => {
            // the same way that the data is passed in props.route,
            // the navigation and it's method to navigate is passed in the props.
            const {navigation} = this.props;
            navigation.navigate('User', {user});
        };
    
    

    Then, the function HandleNavigate redirects to the user page, which is a class component, and I get the data like this:

    import React, {Component} from 'react';
    import {View, Text} from 'react-native';
    
    export default class User extends Component {
        state = {
            title: this.props.route.params.user.name,
        };
    
    
        render() {
            const {title} = this.state;
            return (
                
                    {title}
                
            );
        }
    }
    
    

    In class components, the way I found out is making this quite long line title: this.props.route.params.user.name, but it works. If anyone knows how to make it shorter in the current version of react-native navigation, please enlighten me. I hope this solves your problem.

提交回复
热议问题