页面之间传递参数
实现页面之间传递参数很简单,跟普通的 React 项目一样,具体实例入戏:
// 传入参数
export default function Home(props: { navigation: any }) {return (<View><Text>Home</Text><Buttontitle="切换到详情页"onPress={() =>props.navigation.navigate("Detail Page", {itemId: 86,otherParam: "这是传递过来的参数",})}/></View>);
}// 获取参数
export default function ReviewDetails(props: {navigation: any;route: { params: { itemId: number; otherParam: string } };
}) {return (<View><Text>详情页</Text><Text>itemId: {props.route.params.itemId}</Text><Text>otherParam: {props.route.params.otherParam}</Text><Buttontitle="切换到详情页"onPress={() => props.navigation.push("Detail Page")}/><Buttontitle="返回上一页"onPress={() => props.navigation.goBack()}></Button><Buttontitle="清除所有堆栈信息返回首页"onPress={() => props.navigation.popToTop()}></Button></View>);
}
通过上述的例子可以看出我们实现参数的传递与获取只需要两部:
- 通过将参数放入对象中作为函数的第二个参数来将参数传递给路由
navigation.navigate('RouteName', { 参数 })
- 读取屏幕组件中的参数:
route.params
传递初始参数
您可以将一些初始参数传递给屏幕,如果您在导航到此屏幕时未指定任何参数,则将使用初始参数。它们也与您传递的任何参数浅层合并。初始化参数可以在 Stack.Screen 组件中使用initialParams
属性来实现。具体实例如下:
<Stack.Screenname="Detail Page"component={ReviewDetails}initialParams={{ itemId: 42 }}
/>
参数传递给上一级路由
参数不仅对于将一些数据传递到新屏幕有用,而且对于将数据传递到前一个屏幕也很有用。具体实例如下:
// 首页(接收创建文章页面回传回来的数据)
export default function Home(props: { navigation: any; route: any }) {React.useEffect(() => {if (props.route.params?.post) {console.log(props.route.params?.post);}}, [props.route.params?.post]);return (<View><Text>Home</Text><Text style={{ margin: 10 }}>添加文章页面传回的参数: {props.route.params?.post}</Text><Buttontitle="切换到详情页"onPress={() =>props.navigation.navigate("Detail Page", {itemId: 86,otherParam: "这是传递过来的参数",})}/><Buttontitle="添加文章"onPress={() => props.navigation.navigate("CreateArticle")}></Button></View>);
}// 创建文章
export default function CreateArticle(props: { navigation: any; route: any }) {const [postText, setPostText] = React.useState("");return (<View><TextInputmultilineplaceholder="What's on your mind?"style={{ height: 200, padding: 10, backgroundColor: "white" }}value={postText}onChangeText={setPostText}/><Buttontitle="完成"onPress={() => {props.navigation.navigate({name: "Home Page",params: { post: postText },merge: true,});}}/></View>);
}
通过上述的例子我们可以看到要把参数传递给上一级路由的方法跟我们普通传递参数的方法是一样的。