在React导航中使用navigation.goBack发送参数

问题描述 投票:0回答:5

你好,如何发送参数导航返回?

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。 怎样做?

react-native react-redux react-navigation
5个回答
3
投票

如果您从屏幕 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();
  };
...

1
投票

我是这样做的:

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


0
投票

我基于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>

0
投票

我认为底线是你根本不能使用

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


-1
投票

就我而言,使用通过道具传递的导航和路线,解决方案是:

route.params.onFilter({
    route.params.id,
    details.formatted_address,
    details.geometry
});
navigation.goBack();
© www.soinside.com 2019 - 2024. All rights reserved.