React Navigation 屏幕导航及参数设置、传递

导航到一个新屏幕

function HomeScreen({ navigation }) {
  return (
    
      Home Screen
      
  • navigation - 在native stack navigatornavigation 属性被传递到每一个 screen component (definition) (more about this later in "The navigation prop in depth").
  • 每次你调用push,都会添加一个新的路由到导航堆栈。当你调用navigate时,它首先会尝试找到同名的现有路由,只有在堆栈上还没有新路由时才会推送新路由。

返回屏幕

navigation.goBack();  // 返回上一个屏幕
navigation.popToTop();  // 返回第一个屏幕

屏幕导航时传递参数

方法:

  1. 通过将参数作为导航的第二个参数放在一个对象中,将它们传递给路由。navigation.navigate('RouteName', { /* params go here */ })
  2. 读取屏幕组件中的参数:route.params
onPress={() => {
/* 1. Navigate to the Details route with params */
  navigation.navigate('Details', {
    itemId: 86,
    otherParam: 'anything you want here',
   });
 }}

function DetailsScreen({ route, navigation }) {
  /* 2. Get the param */
  const { itemId, otherParam } = route.params;

更新参数

navigation.setParams({
  query: 'someText',
});

注意:避免使用setParams来更新屏幕选项,如标题等。如果您需要更新选项,请使用setOptions。

初始化屏幕参数


向前一个屏幕传递参数

function HomeScreen({ navigation, route }) {
  React.useEffect(() => {
    if (route.params?.post) {
      // Post updated, do something with `route.params.post`
      // For example, send the post to the server
    }
  }, [route.params?.post]);

  return (
    
      

你可能感兴趣的:(React Navigation 屏幕导航及参数设置、传递)