使用React-Native Navigation传递数据

时间:2017-07-14 18:51:41

标签: javascript android ios reactjs react-native

我试图在我的应用中的屏幕之间传递数据。目前我正在使用

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

我有我的index.ios

import React, { Component } from 'react';
import {
  AppRegistry,
} from 'react-native';
import App from './src/App'
import { StackNavigator } from 'react-navigation';
import SecondScreen from './src/SecondScreen'    

class med extends Component {
  static navigationOptions = {
    title: 'Home Screen',
  };

  render(){
    const { navigation } = this.props;

    return (
      <App navigation={ navigation }/>
    );
  }
}

const SimpleApp = StackNavigator({
  Home: { screen: med },
  SecondScreen: { screen: SecondScreen, title: 'ss' },    
});

AppRegistry.registerComponent('med', () => SimpleApp);

app as

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  Button,
  View
} from 'react-native';
import { StackNavigator } from 'react-navigation';

const App = (props)  => {
  const { navigate } = props.navigation;

  return (
    <View>
      <Text>
        Welcome to React Native Navigation Sample!
      </Text>
      <Button
          onPress={() => navigate('SecondScreen', { user: 'Lucy' })}
          title="Go to Second Screen"
        />
    </View>
  );
}

export default App

然后秒屏幕

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Button
} from 'react-native';

import { StackNavigator } from 'react-navigation';


const SecondScreen = (props)  => {
  const { navigate } = props.navigation;
  console.log("PROPS" + this.props.navigation.state);


  return (
    <View>
      <Text>
        HI
      </Text>

    </View>
  );
}

SecondScreen.navigationOptions = {
  title: 'Second Screen Title',
};

export default SecondScreen

每当我调试console.log时,我都会被定义 https://reactnavigation.org/docs/navigators/navigation-prop 文档说每个屏幕应该具有这些值我做错了什么?

9 个答案:

答案 0 :(得分:12)

所有其他答案现在似乎已过时。在当前的React导航版本("@react-navigation/native": "^5.0.8",)中,您首先需要在一个屏幕与另一个屏幕之间传递值,如下所示:

       function HomeScreen({ navigation }) {
      return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <Text>Home Screen</Text>
          <Button
            title="Go to Details"
            onPress={() => {
              /* 1. Navigate to the Details route with params, passing the params as an object in the method navigate */
              navigation.navigate('Details', {
                itemId: 86,
                otherParam: 'anything you want here',
              });
            }}
          />
        </View>
      );
    }

,然后在要重定向的组件中,您将获得如下传递的数据:

function DetailsScreen({ route, navigation }) {
  /* 2. Get the param */
  const { itemId } = route.params;
  const { otherParam } = route.params;
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <Text>itemId: {JSON.stringify(itemId)}</Text>
      <Text>otherParam: {JSON.stringify(otherParam)}</Text>
    </View>
  );
}

因此,基本上,现在的数据在this.props.route.params内部。在上面的示例中,我展示了如何从功能组件中获取它们,但是在类组件中,我做了类似的事情:

首先,我在此ProfileButton的handleNavigate函数中传递了数据,如下所示:


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

handleNavigate的位置如下:

   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});
    };

然后,函数HandleNavigate重定向到用户页面,该页面是一个类组件,并且我得到如下数据:

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 (
            <View>
                <Text>{title}</Text>
            </View>
        );
    }
}

在类组件中,我发现的方法是制作很长的行title: this.props.route.params.user.name,,但它确实有效。如果有人知道如何在当前版本的本机导航中使其更短,请给我启发。我希望这能解决您的问题。

答案 1 :(得分:11)

在你的代码中,props.navigation和this.props.navigation.state是两回事。你应该在第二个屏幕上试试这个:

const {state} = props.navigation;
console.log("PROPS " + state.params.user);

const {state}行仅用于获取易于阅读的代码。

答案 2 :(得分:8)

头等舱

<Button onPress = {
  () => navigate("ScreenName", {name:'Jane'})
} />

第二课

const {params} = this.props.navigation.state

答案 3 :(得分:5)

反应导航3。*

父母阶级

this.props.navigation.navigate('Child', {
    something: 'Some Value',
});

儿童班

this.props.navigation.state.params.something // outputs "Some Value"

答案 4 :(得分:4)

您可以在相关组件(SecondScreen)中使用user访问您的参数props.navigation.state.params.user

答案 5 :(得分:1)

在react navigaton 3.x docs中,您可以使用getParam(params)

    class SecondScreen extends React.Component {
        render() {
          const { navigation } = this.props;
          const fname = navigation.getParam('user');
          return (
            <View>
              <Text>user: {JSON.stringify(fname)}</Text>
            </View>
          );
        }
    }

答案 6 :(得分:1)

在 2021 年,您可以使用

this.props.route.params.data

答案 7 :(得分:0)

我开发了一个NPM软件包,用于将数据从一个组件发送到其他组件。请检查并使用它易于使用。

React data navigation

import { DataNavigation } from 'react-data-navigation';
.
.
.
// For set the data you need to call setData(key, value) Function i.e.
// eg. DataNavigation.setData('name', 'Viren'); 
// it will set the 'Viren' as respect to 'name' key.

import { DataNavigation } from 'react-data-navigation';
.
.
.
// Here we want to get the name value, which you set in home component than
// console.log('Hey my name is' + DataNavigation.getData('name'));
// it will print in console : Hey my name is Viren.

注释下来以寻求帮助。

答案 8 :(得分:0)

使用钩子

    Screen1.js
    
    navigation.navigate('Screen2',{ user_name: 'aaa',room_id:'100' });
    
    Screen2.js
    
    export default function Screen2({navigation){
              return(
                  <View>
           <Text> {navigation.getParams('user_name')} </Text>
               </View>   
                    )
                  }