React Navigation 主要使用类似于 { userId: 1 } 的 params 对象,而不是像 "/users/:userId" 这样的基于字符串的路由定义。
链接到个人资料
navigation.navigate function 有两个道具:路线的name 和通过的params。如果您要导航到不带任何参数的路线,则根本不需要包含第二个 params 参数。 navigation.navigate("Home") 很好。但是,当转到“用户”路线时,您将始终需要包含 userId。
为了转到特定的用户个人资料,您可以调用:
onPress={() => navigation.navigate("User", { userId: 1 })}
文档:Passing parameters to routes
访问参数
然后可以通过导航器注入的道具在UserScreen 组件中访问userId 参数。每个屏幕都会收到道具route 和navigate。 params 是 route 属性的属性。
所以你可以像这样定义一个UserRoute 组件,我们从route.params.userId 获取当前的userId。
const UserScreen = ({route, navigation}) => (
<View>
<Text>Viewing profile for user #{route.params.userId}</Text>
<TouchableOpacity onPress={() => navigation.navigate("Home")}>
<Text>Back to Home</Text>
</TouchableOpacity>
</View>
);
(Typescript 用户:这个组件是 React.FC<StackScreenProps<RootStackParamList, "User">> 其中RootStackParamList 是您自己的应用程序的参数定义)
声明路由
当您创建路由时,您实际上需要 说明参数。这工作得很好:
export const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="User" component={UserScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
您可以使用一些额外的可选配置。例如,您可以map the params to options 或map the params to a unique screen id。
<Stack.Screen
name="User"
component={UserScreen}
options={({ route }) => ({
title: `User Profile #${route.params.userId}`
})}
getId={({ params }) => params.userId.toString()}
/>
(Typescript 用户会想要定义一个类型,通常称为RootStackParamList,它将每个路由映射到其参数类型。然后将其用作StackScreenProps、StackNavigationProp 等的泛型)
基于字符串的导航
React Navigation确实支持链接到像"/user/1" 这样的路径,但它需要额外的配置。在幕后它仍然使用一个 params 对象,所以你需要 define a mapping 从到 params 的路径。它可以是自定义映射,或者您可以使用与 React Router 对 : 所做的相同语法来定义参数。 "users/:userId" 将创建一个以 userId 为键的 params 对象。
您的Stack.Screen 组件保持不变。配置选项作为属性linking 传递给NavigationContainer 组件。如果你设置了这个,那么你就可以像在 React Router 中一样使用实验性的 Link component 来链接到像 "/users/1" 这样的路径。
export const App = () => {
return (
<NavigationContainer
linking={{
prefixes: ["https://yourdomain.com"],
config: {
screens: {
Home: "",
User: "users/:userId"
}
}
}}
>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="User" component={UserScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
CodeSandbox Demo 带有打字稿类型。