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,
          });
        }}
      />
    </>
  );
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容