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

动态路由

【React Native】动态路由与参数传递_第1张图片

[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 (
    
      这里是首页

      
        跳转传参(Link)
      
      
        跳转传参(Link 使用 params)
      
       router.navigate("/courses/3")}>
        跳转传参(navigate )
      

      
          router.navigate({
            pathname: "/courses/[id]",
            params: { id: 4 },
          })
        }
      >
        跳转传参(navigate 使用 params )
      
    
  );
}

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 (
    
      这里是课程页

      课程ID: {id}
    
  );
}

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',
  },
});

你可能感兴趣的:(跨端开发,react,native,react.js,javascript)