首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何从postlist(posts.js)中获取Id并在react native中的post.js页面上显示

在React Native中,要从postlist(posts.js)中获取Id并在post.js页面上显示,可以按照以下步骤进行操作:

  1. 首先,确保在postlist(posts.js)中,每个帖子的数据都包含一个唯一的Id属性。例如:
代码语言:txt
复制
const posts = [
  { id: 1, title: 'Post 1', content: 'Lorem ipsum dolor sit amet' },
  { id: 2, title: 'Post 2', content: 'Lorem ipsum dolor sit amet' },
  // ...
];
  1. postlist(posts.js)中,将每个帖子渲染为可点击的组件,并在点击时导航到post.js页面,并将对应帖子的Id作为参数传递。例如:
代码语言:txt
复制
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { useNavigation } from '@react-navigation/native';

const PostList = () => {
  const navigation = useNavigation();

  const handlePostPress = (postId) => {
    navigation.navigate('Post', { postId });
  };

  return (
    <View>
      {posts.map((post) => (
        <TouchableOpacity key={post.id} onPress={() => handlePostPress(post.id)}>
          <Text>{post.title}</Text>
        </TouchableOpacity>
      ))}
    </View>
  );
};

export default PostList;
  1. post.js页面中,获取传递的postId参数,并根据该postId查找对应的帖子数据,并在页面上显示。例如:
代码语言:txt
复制
import React from 'react';
import { View, Text } from 'react-native';
import { useRoute } from '@react-navigation/native';

const Post = () => {
  const route = useRoute();
  const { postId } = route.params;

  // 根据postId查找对应的帖子数据
  const post = posts.find((post) => post.id === postId);

  return (
    <View>
      <Text>{post.title}</Text>
      <Text>{post.content}</Text>
    </View>
  );
};

export default Post;

这样,当点击postlist(posts.js)中的帖子时,将导航到post.js页面,并在页面上显示对应帖子的标题和内容。请注意,以上代码中的posts是一个示例数据,你需要根据实际情况进行替换。同时,你还可以根据需要在post.js页面中添加其他UI组件或逻辑。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券