【问题标题】:How to Pass Parameters to screen in StackNavigator?如何将参数传递到 StackNavigator 中的屏幕?
【发布时间】:2017-07-29 11:51:58
【问题描述】:

我的 React Native 代码:

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

我想使用onPress 函数导航到DetailPage。如果我像这样提醒它:

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

我确实得到了值,但是如何将它传递到其他页面?

非常感谢!

【问题讨论】:

标签: react-native react-navigation


【解决方案1】:

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

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

React Navigation 5.x (2020)

通过this.props.route.params 访问它们。例如在你的DetailsPage

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

https://reactnavigation.org/docs/params/

反应导航

通过this.props.navigation.state.params 访问它们。例如在你的DetailsPage:

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

https://reactnavigation.org/docs/4.x/params/

【讨论】:

  • 谢谢。我遇到了一个错误,我尝试了'DetailPage', { users:user });,它成功了。如果你能帮忙,我还有一个问题。我试图使用用户数组中的参数,id 到来自另一个 API 的 fetch 数据,我在哪里以及如何使用它?试图通过声明var theId = '${navigation.state.params.users.id} 来使用fetch,但它不起作用。你能指出我正确的方向吗?非常感谢。
  • 看起来是个错字,试试${navigation.state.params.user.id}user 而不是users
  • 不,我已将其传递为users'DetailPage', { users:user });。不知道在哪里以及如何在fetch 中调用它,请帮助。
  • 我在组件的静态导航选项中的 HeaderRigh 属性上添加了一个按钮,我想传递组件中定义的方法的引用。但我无法通过。你能帮忙吗
  • @RobinGarg 这不是主题,但你会在这个 github 问题中找到解决问题的方法:github.com/react-navigation/react-navigation/issues/147
【解决方案2】:

在反应钩子中,参数使用 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>;
}

【讨论】:

    【解决方案3】:

    See this.

    它解决了我的问题。

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

    【讨论】:

    • 这正是导航的方式。很有用。谢谢
    • 嗨,我在这里尝试使用键传递参数值,但它会引发语法错误。雷克 => 参数:{ "anything_string_or_object" }
    【解决方案4】:

    在你的第一页,说国家列表

    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' 对象将包含您希望从一个屏幕传递到另一个屏幕的所有参数的列表。

    【讨论】:

    • props.route.params 是
    【解决方案5】:

    对我来说,通过 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】:

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

      【讨论】:

        【解决方案7】:

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

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

        【讨论】:

          【解决方案8】:

          你可以很容易地做到这一点。
          您想将一些参数传递给您的屏幕吗?这样做:

          export default () => {
            
            const MainScreenComponent = ({navigation}) => (
              <MainScreen
                navigation={navigation}
                /**
                *
                * And here your parameters...
                *
                */
              />
            );
          
            const HomeScreenComponent = ({navigation}) => (
              <HomeScreen
                navigation={navigation}
                /**
                *
                * And here your parameters...
                *
                */
              />
            );
          
            return (
              <NavigationContainer>
                <Stack.Navigator initialRouteName="MainScreen">
                  <Stack.Screen name="MainScreen" component={MainScreenComponent}/>
                  <Stack.Screen name="HomeScreen" component={MomeScreenComponent}/>
                </Stack.Navigator>
              </NavigationContainer>
            );
          };
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-10-14
            • 2019-07-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多