Navigation prop reference
应用程序中的每个屏幕组件都自动提供导航道具。道具包含各种方便的功能,用于调度导航操作。它是这样的:
· Navigation navigate- 转到另一个屏幕,找出它需要采取的行动
o
o reset - 清除导航器状态并用新的路由替换它
o goBack - 关闭活动屏幕并移回堆栈
o setParams - 修改路由的参数
o dispatch - 发送一个操作对象来更新导航状态
o setOptions - 更新屏幕的选项
o isFocused - 检查屏幕是否对焦
o addListener - 订阅来自导航器的事件更新
需要强调的是,导航道具并没有传递给所有组件;只有屏幕组件自动接收这个道具!React导航在这里没有任何魔力。例如,如果定义MyBackButton组件并将其呈现为屏幕组件的子组件,则无法访问该组件上的导航道具。但是,如果你想在你的任何组件中访问导航道具,你可以使用useNavigation钩子。
setParams/setOptions等只能在useEffect/useLayoutEffect/componentDidMount/componentDidUpdate等中调用。不是在呈现期间或在构造函数中。
· 根据当前导航器的类型,导航道具上还提供了几个附加功能。
· 如果导航器是堆栈导航器,则提供了导航和goBack的几种替代方案,您可以使用自己喜欢的任何一种。函数为:navigation
o replace - 用一个新的路由替换当前的路由
o push - 将一条新路由推入堆栈
o pop - 回到堆栈中
o popToTop - 到堆栈的最上面
如果导航器是一个选项卡导航器,下面也可用:
· navigation
o jumpTo - 转到选项卡导航器中的特定屏幕
如果导航器是一个抽屉式导航器,也可以使用以下导航器
· navigation
o jumpTo - 转到抽屉导航器中的特定屏幕
o openDrawer - 打开
o closeDrawer- 关闭
o toggleDrawer - 切换状态。从关闭切换到打开,反之亦然
您可以在所使用的导航器的文档中找到有关依赖于导航器的函数的更多详细信息。Common API reference
绝大多数与导航道具的交互将涉及navigate、goBack和setParams。
navigate方法让我们在应用程序中导航到另一个屏幕。它接受以下参数:
navigation.navigate(name, params)
name- 已在某处定义的路由的目的地名称
·
params- 传递到目标路由的参数。
·
function HomeScreen({ navigation: { navigate } }) { return ( <View>This is the home screen of the app</Text> <Button onPress={() => navigate('Profile', { names: ['Brent', 'Satya', 'Michaś'] }) } title="Go to Brent's profile" /> </View> );}
Copy
In a native stack navigator, calling navigate with a screen name will result in different behavior based on if the screen is already present or not. If the screen is already present in the stack's history, it'll go back to that screen and remove any screens after that. If the screen is not present, it'll push a new screen.
For example, if you have a stack with the history Home > Profile > Settings and you call navigate(Profile), the resulting screens will be Home > Profile as it goes back to Profile and removes the Settings screen.
By default, the screen is identified by its name. But you can also customize it to take the params into account by using the getId prop.
For example, say you have specified a getId prop for Profile screen:
<Tab.Screen name={Profile} component={ProfileScreen} getId={({ params }) => params.userId} />
Copy
Now, if you have a stack with the history Home > Profile (userId: bob) > Settings and you call navigate(Profile, { userId: 'alice' }), the resulting screens will be Home > Profile (userId: bob) > Settings > Profile (userId: alice) since it'll add a new Profile screen as no matching screen was found.
The goBack method lets us go back to the previous screen in the navigator.
By default, goBack will go back from the screen that it is called from:
function ProfileScreen({ navigation: { goBack } }) { return ( <View> goBack()} title="Go back from ProfileScreen" /> </View> );}
Copy
Going back from a specific screen
Consider the following navigation stack history:
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_A });navigation.navigate({ name: SCREEN, key: SCREEN_KEY_B });navigation.navigate({ name: SCREEN, key: SCREEN_KEY_C });navigation.navigate({ name: SCREEN, key: SCREEN_KEY_D });
Copy
Now you are on screen D and want to go back to screen A (popping D, C, and B). Then you can use navigate:
navigation.navigate({ key: SCREEN_KEY_A}); // will go to screen A FROM screen D
Copy
Alternatively, as screen A is the top of the stack, you can use navigation.popToTop().
The reset method lets us replace the navigator state with a new state:
navigation.reset({index: 0,routes: [{ name: 'Profile' }],});
Copy
The state object specified in reset replaces the existing navigation state with the new one, i.e. removes existing screens and add new ones. If you want to preserve the existing screens when changing the state, you can use CommonActions.reset with dispatch instead.
Note: Consider the navigator's state object to be internal and subject to change in a minor release. Avoid using properties from the navigation state object except index and routes, unless you really need it. If there is some functionality you cannot achieve without relying on the structure of the state object, please open an issue.
The setParams method lets us update the params (route.params) of the current screen. setParams works like React's setState - it shallow merges the provided params object with the current params.
function ProfileScreen({ navigation: { setParams } }) { return ( <Button onPress={() => setParams({ friends: route.params.friends[0] === 'Brent' ? ['Wojciech', 'Szymon', 'Jakub'] : ['Brent', 'Satya', 'Michaś'], title:route.params.title === "Brent's Profile"? "Lucy's Profile": "Brent's Profile", }) } title="Swap title and friends" /> );}
Copy
The setOptions method lets us set screen options from within the component. This is useful if we need to use the component's props, state or context to configure our screen.
function ProfileScreen({ navigation, route }) { const [value, onChangeText] = React.useState(route.params.title); React.useEffect(() => { navigation.setOptions({title: value === ''? 'No title' : value, }); }, [navigation, value]); return (
Copy
Any options specified here are shallow merged with the options specified when defining the screen.
When using navigation.setOptions, we recommend specifying a placeholder in the screen's options prop and update it using navigation.setOptions. This makes sure that the delay for updating the options isn't noticeable to the user. It also makes it work with lazy-loaded screens.
You can also use React.useLayoutEffect to reduce the delay in updating the options. But we recommend against doing it if you support web and do server side rendering.
Note: navigation.setOptions is intended to provide the ability to update existing options when necessary. It's not a replacement for the options prop on the screen. Make sure to use navigation.setOptions sparingly only when absolutely necessary.
Screens can add listeners on the navigation prop with the addListener method. For example, to listen to the focus event:
function Profile({ navigation }) { React.useEffect(() => { const unsubscribe = navigation.addListener('focus', () => { // do something }); return unsubscribe; }, [navigation]); return <ProfileContent />;}
Copy
See Navigation events for more details on the available events and the API usage.
This method lets us check whether the screen is currently focused. Returns true if the screen is focused and false otherwise.
const isFocused = navigation.isFocused();
Copy
This method doesn't re-render the screen when the value changes and mainly useful in callbacks. You probably want to use useIsFocused instead of using this directly, it will return a boolean a prop to indicating if the screen is focused.
The dispatch function is much less commonly used, but a good escape hatch if you can't do what you need with the available methods such as navigate, goBack etc. We recommend to avoid using the dispatch method often unless absolutely necessary.
The dispatch method lets us send a navigation action object which determines how the navigation state will be updated. All of the navigation functions like navigate use dispatch behind the scenes.
Note that if you want to dispatch actions you should use the action creators provided in this library instead of writing the action object directly.
See Navigation Actions Docs for a full list of available actions.
import{ CommonActions } from '@react-navigation/native';navigation.dispatch( CommonActions.navigate({name: 'Profile', params: {}, }));
Copy
When dispatching action objects, you can also specify few additional properties:
· source - The key of the route which should be considered as the source of the action. For example, the replace action will replace the route with the given key. By default, it'll use the key of the route that dispatched the action. You can explicitly pass undefined to override this behavior.
· target - The key of the navigation state the action should be applied on. By default, actions bubble to other navigators if not handled by a navigator. If target is specified, the action won't bubble if the navigator with the same key didn't handle it.
Example:
import{ CommonActions } from '@react-navigation/native';navigation.dispatch({ ...CommonActions.navigate('Profile'),source: 'someRoutekey',target: 'someStatekey',});
Copy
It's also possible to pass a action creator function to dispatch. The function will receive the current state and needs to return a navigation action object to use:
import{ CommonActions } from '@react-navigation/native';navigation.dispatch((state) => { // Add the home route to the start of the stack constroutes = [{ name: 'Home' }, ...state.routes]; return CommonActions.reset({ ...state, routes,index: routes.length - 1, });});
Copy
You can use this functionality to build your own helpers that you can utilize in your app. Here is an example which implements inserting a screen just before the last one:
import{ CommonActions } from '@react-navigation/native';const insertBeforeLast = (routeName, params) => (state) => { const routes = [ ...state.routes.slice(0, -1), { name: routeName, params },state.routes[state.routes.length - 1], ]; return CommonActions.reset({ ...state, routes,index: routes.length - 1, });};
Copy
Then use it like:
navigation.dispatch(insertBeforeLast('Home'));
Copy
This method returns a boolean indicating whether there's any navigation history available in the current navigator, or in any parent navigators. You can use this to check if you can call navigation.goBack():
if (navigation.canGoBack()) { navigation.goBack();}
Copy
Don't use this method for rendering content as this will not trigger a re-render. This is only intended for use inside callbacks, event listeners etc.
This method returns the navigation prop from the parent navigator that the current navigator is nested in. For example, if you have a stack navigator and a tab navigator nested inside the stack, then you can use getParent inside a screen of the tab navigator to get the navigation prop passed from the stack navigator.
It accepts an optional ID parameter to refer to a specific parent navigator. For example, if your screen is nested with multiple levels of nesting somewhere under a drawer navigator with the id prop as "LeftDrawer", you can directly refer to it without calling getParent multiple times.
To use an ID for a navigator, first pass a unique id prop:
<Drawer.Navigator id="LeftDrawer"> {/* .. */}</Drawer.Navigator>
Copy
Then when using getParent, instead of:
// Avoid thisconst drawerNavigation = navigation.getParent().getParent();// ...drawerNavigation?.openDrawer();
Copy
You can do:
// Do thisconst drawerNavigation = navigation.getParent('LeftDrawer');// ...drawerNavigation?.openDrawer();
Copy
This approach allows components to not have to know the nesting structure of the navigators. So it's highly recommended that use an id when using getParent.
This method will return undefined if there is no matching parent navigator. Be sure to always check for undefined when using this method.
Note: Consider the navigator's state object to be internal and subject to change in a minor release. Avoid using properties from the navigation state object except index and routes, unless you really need it. If there is some functionality you cannot achieve without relying on the structure of the state object, please open an issue.
This method returns the state object of the navigator which contains the screen. Getting the navigator state could be useful in very rare situations. You most likely don't need to use this method. If you do, make sure you have a good reason.
If you need the state for rendering content, you should use useNavigationState instead of this method.
网友评论