Link
- 跳轉的路徑,就在
href
里寫/details
。 - 路徑都是相對于
app
目錄來寫的,也就是說app
目錄就是/
。 - 很多時候,需要跳轉的組件比較復雜。比方說,要在里面要嵌套按鈕,或者其他東西。這種情況下,就可以在
Link
組件里加個asChild
。
import { Link } from "expo-router";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";export default function Index() {return (<View style={styles.container}><Text style={styles.title}>這里是首頁</Text><Link href="/details" style={styles.link}>跳轉到詳情頁(Link)</Link><Link href="/details" asChild><TouchableOpacity><Text style={styles.buttonText}>跳轉到詳情頁(Link + asChild)</Text></TouchableOpacity></Link></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 { Link } from "expo-router";
import { StyleSheet, Text, View } from "react-native";export default function Details() {return (<View style={styles.container}><Text style={styles.title}>這里是詳情頁</Text><Link href="../" style={styles.backText}>返回</Link></View>);
}const styles = StyleSheet.create({container: {flex: 1,backgroundColor: "#fff",alignItems: "center",justifyContent: "center",},title: {fontSize: 40,fontWeight: "bold",color: "#4f9df7",},backText: {marginTop: 20,fontSize: 20,color: "#67c1b5",},
});
router
方法 | 作用 | 說明 |
---|---|---|
router.navigate | 跳轉到指定頁面,最常用。 | 如果目標頁面已在Stack中,直接跳轉到現有實例,否則新增頁面到Stack。 |
router.replace | 替換掉Stack中所有頁面。 | 因為Stack里之前的頁面都被替換了,無法返回上一頁。 |
router.push | 強制新增頁面到Stack。 | 無論目標頁面是否存在,始終在Stack里新增一個頁面。 |
router.dismiss | 關閉當前的頁面,返回Stack里的上一個頁面。 | |
router.dismissAll | 關閉所有中間頁面,返回Stack根頁面。 |
此外還有一些不太常用的方法:
router.dismiss(2)
,可以在dismiss
里加數字,表示返回幾層。router.dismissTo('/')
,表示從當前頁返回到目標頁面,并關閉中間頁面。
import { useRouter } from "expo-router";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";export default function Index() {const router = useRouter();return (<View style={styles.container}><Text style={styles.title}>這里是首頁</Text><TouchableOpacity onPress={() => router.navigate('/details')}><Text style={styles.buttonText}>跳轉(navigate )</Text></TouchableOpacity><TouchableOpacity onPress={() => router.replace('/details')}><Text style={styles.buttonText}>替換(replace)</Text></TouchableOpacity></View>);
}const styles = StyleSheet.create({container: {flex: 1,backgroundColor: "#fff",alignItems: "center",justifyContent: "center",},title: {fontSize: 40,fontWeight: "bold",color: "#e29447",},buttonText: {marginTop: 20,fontSize: 25,color: "#ff7f6f",},
});