react-native - 如何使用 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
}
});
解决方案
您可以在反应导航 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'
}
});
推荐阅读
- python - 使用请求时出现 MissingSchema 异常
- python - 如何使用 xarray.apply_ufunc() 将 1D 中值滤波器应用于 3D DataArray
- javascript - 如何在 php 中使用 jquery 更新当前日期
- regex - 如何通过熊猫从列输出中删除某些字符串集
- php - 我们可以在函数声明时使用 (-) 符号吗
- swift - 如何以编程方式为我在容器视图中调用的 ViewController 设置约束?
- html - 如何从管理站点在站点上显示文本?
- javascript - 我正在尝试映射对象,嵌套在嵌套在数组中的对象中。解决这个问题的最佳方法是什么?
- python - 如何使用 base64 模块获取带有“\”的解码字符串
- c# - C# 动态类型 Object 属性 First 始终为 null