首页 > 解决方案 > 如何使用 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。

标签: javascriptreactjsreact-nativereact-navigation

解决方案


这可能会有所帮助

// ./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... -->
    />
  );
};}

推荐阅读