首页 > 解决方案 > 如何使用 react-navigation v5 获取 id 的参数?

问题描述

我正在尝试更新我使用 react-navigation v4 开发的应用程序。

使用 react-navigation v4 我可以使用类似 console.log(navigation.getParam('id'));

但是当我在更新到 react-navigation 的 v5 后尝试相同的操作时,它向我显示一个错误,我找不到获取参数 ID 的正确方法

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

export default function ShowScreen({ navigation }) {
  console.log(navigation.getParam('id'));

  return (
    <View style={styles.container}>
      <Text>Show Screen</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  }
});

id所在的另一个屏幕是它:

import React, { useContext } from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import { FlatList, TouchableOpacity } from 'react-native-gesture-handler';

import { Context } from '../../context/BlogContext';

import Icon from 'react-native-vector-icons/Feather'

export default function IndexScreen({ navigation }) {
  const { state, addBlogPost, deleteBlogPost } = useContext(Context);

  return (
    <View style={styles.container}>
      <Button
        title="Add Post"
        onPress={addBlogPost}
      />
      <FlatList
        data={state}
        keyExtractor={(blogPost) => blogPost.title}
        renderItem={({ item }) => {
          return (
            <TouchableOpacity onPress={
              () => navigation.navigate('ShowScreen',
                { id: item.id })}>
              <View style={styles.row}>
                <Text style={styles.title}>
                  {item.title} -
                  {item.id}
                </Text>
                <TouchableOpacity onPress={() => deleteBlogPost(item.id)}>
                  <Icon style={styles.icon}
                    name="trash"
                  />
                </TouchableOpacity>
              </View>
            </TouchableOpacity>
          );
        }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 30,
    justifyContent: 'center',
    alignItems: 'center'
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: 10,
    paddingVertical: 20,
    borderTopWidth: 1,
    borderColor: '#333'
  },
  title: {
    fontSize: 18
  },
  icon: {
    fontSize: 24
  }
});

标签: react-nativeparametersreact-propsreact-navigation-v5

解决方案


您可以在反应导航 v5 中使用 route.params 获取参数,更多内容请阅读此处

只需将您的代码更新为此

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

export default function ShowScreen({ navigation,route }) {
  const {id} =route.params; //you will get id here via route

  return (
    <View style={styles.container}>
      <Text>Show Screen</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  }
});

推荐阅读