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

导航到一个新屏幕

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}
  • 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。

初始化屏幕参数

<Stack.Screen
  name="Details"
  component={DetailsScreen}
  initialParams={{ itemId: 42 }}
/>

向前一个屏幕传递参数

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 (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button
        title="Create post"
        onPress={() => navigation.navigate('CreatePost')}
      />
      <Text style={{ margin: 10 }}>Post: {route.params?.post}</Text>
    </View>
  );
}

function CreatePostScreen({ navigation, route }) {
  const [postText, setPostText] = React.useState('');

  return (
    <>
      <TextInput
        multiline
        placeholder="What's on your mind?"
        style={{ height: 200, padding: 10, backgroundColor: 'white' }}
        value={postText}
        onChangeText={setPostText}
      />
      <Button
        title="Done"
        onPress={() => {
          // Pass and merge params back to home screen
          navigation.navigate({
            name: 'Home',
            params: { post: postText },
            merge: true,
          });
        }}
      />
    </>
  );
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容