React Navigation 入门(四) - 屏幕导航 Navigation 属性详解
之前已经说过,每个在 navigator 中注册过的页面都会接受一个 navigation 属性,它包含以下几属性:
在之前的几篇文章中,我们已经接触过 注意: 与 Redux 集成时的注意事项
navigate - 链接其他屏幕在 app 中跳转其它页面时调用的方法。它有如下参数:
class HomeScreen extends React.Component {
render() {
const {navigate} = this.props.navigation;
return (
<View>
<Text>This is the home screen of the app</Text>
<Button
// 跳转到 Profile 页面并传递参数 name
onPress={() => navigate('Profile',{name: 'Brent'})}
title="Go to Brent's profile"
/>
</View>
)
}
}
state - 屏幕当前状态/路由一个屏幕可以通过 {
// the name of the route config in the router
// 路由器中设置的路由名称
routeName: 'Profile',// a unique identifier used to sort routes
// 为方便管理路由而产生的唯一标识
key: 'main0',// an optional object of string options for this screen
// 给当前屏幕可供选择的参数对象
params: { hello: 'world' }
}
class ProfileScreen extends React.Component {
render() {
const {state} = this.props.navigation;
// state.routeName === 'Profile'
return (
// 获取参数 name,我们之前已经见到过这种用法了
<Text>Name: {state.params.name}</Text>
);
}
}
setParams - 改变路由参数触发 class ProfileScreen extends React.Component {
render() {
const {setParams} = this.props.navigation;
return (
<Button
onPress={() => setParams({name: 'Lucy'})}
title="Set title name to 'Lucy'"
/>
)
}
}
goBack - 关闭当前活动页面并返回给该方法提供一个 key,来决定要从哪个路由返回(即要关闭哪个页面)。默认情况下,会关闭掉调用该方法的当前路由。如果目标是想要回到 anywhere 而不具体地说明要关闭哪个页面,可以调用 class HomeScreen extends React.Component {
render() {
const {goBack} = this.props.navigation;
return (
<View>
<Button
// 关闭当前的 HomeScreen
onPress={() => goBack()}
title="Go back from this HomeScreen"
/>
<Button
// 这里测试的结果也是关闭了当前的 HomeScreen
onPress={() => goBack(null)}
title="Go back anywhere"
/>
<Button
// 关闭从 'screen-123' 到栈顶的所有路由
onPress={() => goBack('screen-123')}
title="Go back from screen-123"
/>
</View>
)
}
}
从指定的页面返回 假设我们有四个路由 A B C D 依次入栈: navigation.navigate(SCREEN_KEY_A);
...
navigation.navigate(SCREEN_KEY_B);
...
navigation.navigate(SCREEN_KEY_C);
...
navigation.navigate(SCREEN_KEY_D);
假如你在 screen D 并且想要返回到 screen A(关闭 D,C 和 B),那么你就需要这么写: // will go to screen A FROM screen B
navigation.goBack(SCREEN_KEY_B)
注意:这个方法里面的 key 值,并不是定义 navigator 时我们给页面自定义的 key,而是上面 state 里面的 dispatch - 给路由发送一个行为使用 dispatch 给路由指派任意的 navigation 行为,其它的 navigation 函数使用后台的 dispatch 来实现。记住如果你想指派 react-navigation 行为的话,你应该使用库里提供的 action creators。查看 Navigation Actions 来获取完整的可指派行为(具体行为会在下一篇文章进行说明)。 import { NavigationActions } from 'react-navigation'
const navigateAction = NavigationActions.navigate({
routeName: 'Profile',params: {},// navigate can have a nested navigate action that will be run inside the child router
// navigate 可以嵌套 navigate action,它会在子路由里面执行
action: NavigationActions.navigate({ routeName: 'SubProfileRoute'})
})
this.props.navigation.dispatch(navigateAction)
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |