如何在StackNavigator中将参数传递给屏幕?

时间:2017-07-29 11:51:58

标签: react-native react-navigation

My React Native code:

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

import { StackNavigator } from 'react-navigation';
import DetailsPage from './src/screens/DetailsPage';

class HomeScreen extends React.Component {

   constructor() {
    super();
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      userDataSource: ds,
    };
  }

  componentDidMount(){
      this.fetchUsers();
  }

    fetchUsers(){

        fetch('https://jsonplaceholder.typicode.com/users')
            .then((response) => response.json())
            .then((response) => {
                this.setState({
                    userDataSource: this.state.userDataSource.cloneWithRows(response)
                });
            });
    }

    onPress(user){
        this.props.navigator.push({
            id: 'DetailPage'
        });
    }

  renderRow(user, sectionID, rowID, highlightRow){
      return(
      <TouchableHighlight onPress={()=>{this.onPress(user)} } >
      <View style={styles.row}>
        <Text style={styles.rowText}> {user.name} </Text>

      </View>
      </TouchableHighlight>
      )
  }


  render(){
      return(
          <ListView
            dataSource = {this.state.userDataSource}
            renderRow = {this.renderRow.bind(this)}
          />
      )
  } 
}

导航配置:

const NavigationTest = StackNavigator({
  Home: { screen: HomeScreen },
  DetailsPage: { screen: DetailsPage },
});

详细信息屏幕是:

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

import styles from '../styles';


export default class DetailsPage extends React.Component {
  static navigationOptions = ({ navigation }) => ({
    title: `User: ${navigation.state.params.user.name}`,
  });
  render() {
    const { params } = this.props.navigation.state;
    return (
      <View>
        <Text style={styles.myStyle}>Name: {params.name}</Text>
        <Text style={styles.myStyle}>Email: {params.email}</Text>
      </View>
    );
  }
}

我无法使用代码将user传递给DetailsPage

onPress(user){
        this.props.navigator.push({
            id: 'DetailPage'
        });
    }

我想使用DetailPage功能导航到onPress。如果我提醒它:

onPress(user){ Alert.alert(user.name)}

我确实得到了这个值,但是如何将其传递到另一个页面呢?

非常感谢!

8 个答案:

答案 0 :(得分:51)

您可以使用navigate函数的第二个参数传递params:

onPress(user) {
  this.props.navigation.navigate(
    'DetailPage',
    { user },
  );
}

然后在this.props.navigation.state.params中访问它们。例如,在DetailsPage

<Text style={styles.myStyle}>{this.props.navigation.state.params.user.name}</Text>

参考:https://reactnavigation.org/docs/params.html

答案 1 :(得分:6)

在react挂钩中,参数使用useNavigation发送导航

import { useNavigation } from '@react-navigation/native';

const navigation = useNavigation();

<Button
      title="Back"
      onPress={() => {
        navigation.navigate('MyScreen',{name:'test'});
      }}
    />

然后使用useNavigationParam访问它们

function MyScreen() {
  const name = useNavigationParam('name');
  return <p>name is {name}</p>;
}

答案 2 :(得分:2)

See this

它解决了我的问题。

this.props.navigation.navigate("**stack_Name**", {
 screen:"screen_name_connect_with_**stack_name**",
 params:{
 user:"anything_string_or_object"
}
})

答案 3 :(得分:0)

您可以使用react-navigation-helper轻松获取参数:

示例:

import { StackNavigator } from 'react-navigation';
import { StackNavigatorHelper } from 'react-navigation-helper';

import { Scene1, Scene2 } from './src';

export default StackNavigatorHelper.exportStackNavigator(
    StackNavigator(
        {
            Scene1: { screen: StackNavigatorHelper.setInitParamsToProps(Scene1) },
            Scene2: { screen: StackNavigatorHelper.paramsToProps(Scene2) }
        }
    )
);

并获取以下参数:

const parameterName = this.props.parameterName

链接:react-navigation-helper

答案 4 :(得分:0)

在您的第一页中,说国家列表

const CountriesList = ({ navigation }) => {

/* Function to navigate to 2nd screen */
  const viewCountry = (country) => {
    navigation.navigate('ListItemPageRoute', { name: country.country_name });
  };
}

输入第二个页面名称,例如ListItemPageRoute

const ListItemPageRoute = (props) => {

return (
    <View style={styles.container}>
        <Text style={styles.countryText}> { props.route.params.name } </Text>
    </View>
  );
};

“ Props.route”对象将包含您希望从一个屏幕传递到另一屏幕的所有参数的列表。

答案 5 :(得分:0)

对我来说,通过useNavigation()和useRoute()进行保存:

对于功能组件:

import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';

function MyBackButton() {
  const navigation = useNavigation();

  return (
    <Button
      title="Back"
      onPress={() => {
        navigation.goBack();
      }}
    />
  );
}

对于课程组件:

class MyText extends React.Component {
  render() {
    // Get it from props
    const { route } = this.props;
  }
}

// Wrap and export
export default function(props) {
  const route = useRoute();

  return <MyText {...props} route={route} />;
}

答案 6 :(得分:0)

onPress = {()=> {this.props.navigation.navigate('AllImages',{Types:item.type})} console.log('values strong text ',this.props.route.params.Types); **

答案 7 :(得分:0)

1)如何通过参数将数据发送到另一个屏幕: onPress={(item) => props.navigation.navigate('Your ScreenName', {item : item})}

2)如何在另一个屏幕上获取数据: const {item} = props.route.params