javascript - 如何使用 React Native Navigation 从 FlatList 组件导航到扩展组件
问题描述
我正在使用 ReactNative 创建一个基本的博客应用程序。主屏幕呈现带有标题、关键字和作者的帖子的 FlatList。我希望能够单击单个帖子并导航到包含完整博客帖子的新屏幕。我将尝试提供尽可能多的代码来解释我的问题。
// ./Post
function Post(props) {
const navigation = useNavigation();
return (
<TouchableOpacity
style={styles.container}
onPress={() =>
navigation.navigate({ name: "ExpandedPost", params: props.id })
}
>
<View>
<Text style={styles.post}>This is the title to a fake post</Text>
<Text style={styles.text}>By {props.Author} </Text>
</View>
<Image
source={{ uri: "https://picsum.photos/200/300" }}
style={styles.thumbnail}
/>
</TouchableOpacity>
);
}
// ./ExpandedPost
export default function ExpandedPost({ navigation, route }) {
return (
<View style={styles.container}>
<View>
<Text style={styles.post}>This is the title to a fake post</Text>
<Text> This is a body of a fake post</Text>
</View>
<Image
source={{ uri: "https://picsum.photos/200/300" }}
style={styles.thumbnail}
/>
</View>
);
}
// ./PostList
const RenderPosts = () => {
return (
<FlatList
data={fakePosts}
renderItem={({ item }) => <Post Author={item.Author} />}
/>
);
};
export default function PostList() {
return (
<View style={styles.container}>
<Header />
<RenderPosts />
</View>
);
}
基本上,我想获取在 PostList 中呈现的帖子,并且我想在 onPress 上导航到包含来自特定帖子的所有数据的 ExpandedPost。
解决方案
这可能会有所帮助
// ./Post
function Post(props) {
const navigation = useNavigation();
return (
<TouchableOpacity
style={styles.container}
onPress={() =>
navigation.navigate("ExpandedPost", {item: props.item})
}
>
<View>
<Text style={styles.post}>This is the title to a fake post</Text>
<Text style={styles.text}>By {props.item.Author} </Text> <-- Change here -->
</View>
...
</TouchableOpacity>
);
}
// ./ExpandedPost
export default function ExpandedPost(props) {
const completeItemOfPost = props.item; <-- Complete Item Here -->
return (
<View style={styles.container}>
<View>
<Text style={styles.post}>This is the title to a fake post</Text> <-- You can show title like "completeItemOfPost.title" -->
<Text> This is a body of a fake post</Text> <-- You can show body like "completeItemOfPost.body" -->
</View>
<Image
source={{ uri: "https://picsum.photos/200/300" }} <-- You can show image like "completeItemOfPost.image" -->
style={styles.thumbnail}
/>
</View>
);
}
// ./PostList
const RenderPosts = () => {
return (
<FlatList
data={fakePosts}
renderItem={({ item }) => <Post item={item} />} <-- Pass complete item here... -->
/>
);
};}
推荐阅读
- c# - 如何使用 GridUnitType.Star 在网格长度上执行动画?
- php - 在 php 7+ 中使用 sqlsrv 执行存储过程
- python - 如何通过计数过滤熊猫 DF 并同时平均组?
- sas - SAS dsnless 通过传入凭据连接到 SQL Server
- javascript - 数组中的元素自动更新
- validation - 如何从 Hybris 1905 中删除 CustomerName 验证,这样当我创建一个客户时,我可以在没有名称的情况下执行它?
- c++ - 选择排序算法产生乱序结果
- c# - VB .Net 无法在非托管 DLL 的方法中引用 byte* 指针
- transparency - 使用 Geopandas 绘制 shapefile 时 Alpha 透明度不均匀
- json - fullcalendar dayClick 函数在 ajax 调用 json 数据中不起作用