【React Native】动态路由与参数传递

发布于:2025-07-18 ⋅ 阅读:(25) ⋅ 点赞:(0)

动态路由

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

[id].js文件是个动态路由文件。

使用:

  • /courses/1
  • /courses/2

都是可以匹配上的,也就说它的最后一个参数是不确定的,可以是任意值。

参数传递

import { View, Text, StyleSheet, TouchableOpacity } from "react-native";
import { Link, useRouter } from "expo-router";

export default function Index() {
  const router = useRouter();

  return (
    <View style={styles.container}>
      <Text style={styles.title}>这里是首页</Text>

      <Link style={styles.link} href="/courses/1">
        跳转传参(Link)
      </Link>
      <Link
        style={styles.link}
        href={{
          pathname: "/courses/[id]",
          params: { id: 2 },
        }}
      >
        跳转传参(Link 使用 params)
      </Link>
      <TouchableOpacity onPress={() => router.navigate("/courses/3")}>
        <Text style={styles.buttonText}>跳转传参(navigate )</Text>
      </TouchableOpacity>

      <TouchableOpacity
        onPress={() =>
          router.navigate({
            pathname: "/courses/[id]",
            params: { id: 4 },
          })
        }
      >
        <Text style={styles.buttonText}>跳转传参(navigate 使用 params )</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  title: {
    fontSize: 40,
    fontWeight: "bold",
    color: "#e29447",
  },
  link: {
    marginTop: 20,
    fontSize: 20,
    color: "#1f99b0",
  },
  buttonText: {
    marginTop: 20,
    fontSize: 20,
    color: "#ff7f6f",
  },
});
import { View, Text, StyleSheet } from 'react-native';
import { useLocalSearchParams } from 'expo-router';

export default function Course() {
  const { id } = useLocalSearchParams();

  return (
    <View style={styles.container}>
      <Text style={styles.title}>这里是课程页</Text>

      <Text style={styles.info}>课程ID: {id}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 40,
    fontWeight: 'bold',
    color: '#4f9df7',
  },
  info: {
    marginTop: 20,
    fontSize: 20,
    color: '#67c1b5',
  },
});

网站公告

今日签到

点亮在社区的每一天
去签到