react-navigator学习总结

react-navigator学习总结
 最后更新于 2024年10月03日 02:55:57

路由

通用API

this.props.navigation

  • navigate - 转到另一个屏幕, 计算出需要执行的操作
  • goBack - 关闭活动屏幕并在堆栈中向后移动
  • addListener - 订阅导航生命周期的更新
  • isFocused - 函数返回 true 如果屏幕焦点和 false 否则。
  • state - 当前状态/路由
  • setParams - 对路由的参数进行更改
  • getParam - 获取具有回退的特定参数
  • dispatch - 向路由发送 action
  • dangerouslyGetParent - function that returns the parent navigator, if any

stack navigator 栈导航器API

this.props.navigation

  • push - push a new route onto the stack
  • pop - 返回堆栈中的上一个页面
  • popToTop - 跳转到堆栈中最顶层的页面
  • replace - 用新路由替换当前路由
  • reset - wipe the navigator state and replace it with the result of several actions
  • dismiss - dismiss the current stack

drawer navigator 抽屉导航器API

this.props.navigation

  • openDrawer - open the drawer
  • closeDrawer - close the drawer
  • toggleDrawer - toggle the state, ie. switch from closed to open and vice versa

路由跳转

navigation.navigate({ routeName, params, action, key })
// or
navigation.navigate(routeName, params, action)
  • routeName - 已在路由器中注册的路由名
  • params - 路由中的参数
  • action - (advanced) The sub-action to run in the child router, if the screen is a navigator. See Actions Doc for a full list of supported actions.
  • key - Optional identifier of what route to navigate to. Navigate back to this route, if it already exists

摘要

  • this.props.navigation.navigate('RouteName') 将新路由推送到堆栈导航器。该方法首先在 stack navigator 中查找定义了 RouteName 的路由,若不存在则不会发生任何事情;如果当前已经在 RouteName 页面中,也不会跳转。所以只有在堆栈上没有该路由时才会推送该路由。
  • 可以多次调用 this.props.navigation.push('RouteName'),并且它会继续跳转路由。
  • 标题栏会自动显示返回按钮,但可以通过调用 this.props.navigation.goBack() 以编程方式返回。在Android上,硬件返回按钮会按预期工作。
  • 可以使用 this.props.navigation.navigate('RouteName') 返回堆栈中的现有页面,也可以使用 this.props.navigation.popToTop() 返回堆栈中的第一个页面。
  • navigation prop适用于所有屏幕组件(组件定义为路由配置中的屏幕,并且被 React Navigation 渲染为路由)。

其他问题

1、在Android上页面跳转如何实现iOS左右切换的效果

import StackStyleInterpolator from 'react-navigation-stack/dist/views/StackView/StackViewStyleInterpolator.js';

createStackNavigator({
}, {
  mode: 'card',
  headerMode: 'screen',
  initialRouteName: 'Home',
  transitionConfig: () => ({
    // 设置横向切换动画
    screenInterpolator: StackStyleInterpolator.forHorizontal
  })
})