你好,如何发送参数导航返回?
const Onsubmit = (data, details = null) => {
console.log(details.formatted_address);
route.params.onPlaceChosen(
route.params.id,
details.formatted_address,
details.geometry
);
navigation.goBack();
};
这里我想将details.formatted_address中的值传递到页面B。 怎样做?
如果您从屏幕 A 导航到屏幕 B,并且当您想返回屏幕 A 并再次在屏幕 A 中运行回调时,您需要执行以下操作:
在屏幕 A(源)中
...
const onPlaceChosen = (params) => {
// here is your callback function
}
...
navigation.navigate('ScreenB', { onPlaceChosen })
...
在您的屏幕 B(目的地)中
..
const Onsubmit = (data, details = null) => {
navigation.state.params.onPlaceChosen(
route.params.id,
details.formatted_address,
details.geometry
);
navigation.goBack();
};
...
我是这样做的:
onPress={() => {
// Pass and merge params back to home screen
navigation.navigate({
name: 'Home',
params: { post: postText },
merge: true,
});
}}
摘自: https://reactnavigation.org/docs/params#passing-params-to-a-previous-screen
我基于https://reactnavigation.org/docs/5.x/hello-react-navigation/#passing-additional-props
做了类似的事情const [params, setParams] = useState({});
<Stack.Navigator>
<Stack.Screen name="One">
{props => <FirstScreen {...props} paramsFromTwo={params} />}
</Stack.Screen>
<Stack.Screen name="Two">
{props => <SecondScreen {...props} onGoBack={(paramsFromSecond} => setParams(paramsFromSecond)} />}
</Stack.Screen>
</Stack.Navigator>
我认为底线是你根本不能使用
goBack()
来传递参数,你必须使用 navigate()
来传递参数。
但是你必须计算之前的路线,我认为还没有人提到如何做。这对我有用:
// get previous route
const routes = navigation.getState().routes;
const previousRoute = routes[routes.length - 2];
// navigate to previous route with param functionality
navigation.navigate({
name: previousRoute?.name ?? "",
params: {
someParam
},
merge: true // merge new params with previous page params
});
就我而言,使用通过道具传递的导航和路线,解决方案是:
route.params.onFilter({
route.params.id,
details.formatted_address,
details.geometry
});
navigation.goBack();