前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >react-navigation 使用笔记 持续更新中

react-navigation 使用笔记 持续更新中

作者头像
木子墨
发布2018-12-12 13:55:52
7630
发布2018-12-12 13:55:52
举报

目录

  • 基本使用(此处基本使用仅针对导航头部而言,不包含tabbar等)
  • header怎么和app中通信呢?

React-Navigation是目前React-Native官方推荐的导航组件,代替了原用的Navigator。最近开始接触,做个笔记


基本使用(此处基本使用仅针对导航头部而言,不包含tabbar等)

基础使用主要包括两部分

组件引入与定义路由

组件引入后,可以通过提供的api createStackNavigator来创建路由,每个路由元素都是一个对象

代码语言:javascript
复制
import { createStackNavigator } from 'react-navigation';
export default createStackNavigator({
  Home: {
    screen: App
  },
  Demos: {
    screen: demo
  },
  DebugList: DebugList,
  DebugDetail: DebugDetail
})
自定义header内容

在每个具体的页面中,可以通过设置navigationOptions对象来对header进行一定程度的自定义

代码语言:javascript
复制
static navigationOptions={
  headerTintColor:'#000',
  headerTitle: (
    <Text style={{ flex: 1, textAlign: 'center', color: '#222222', fontSize: px2dp(18)}}>调试demo</Text>
  ),
  headerRight: <View/>
};
--or--
static navigationOptions = ({ navigation, screenProps }) => {
  return {
    headerTintColor:'#000',
    headerTitle: (
      <Text style={{ flex: 1, textAlign: 'center', color: '#222222', fontSize: px2dp(18) }}>网络日志</Text>
    ),
    // 这里之所以要判断 是因为在生命周期最开始的时候 这个params我们还没给他绑定点击事件
    headerRight: <View><Text onPress={navigation.state.params?navigation.state.params.navigatePress:null}>清空</Text></View>
  }
}

可以通过对象或者函数两种形式进行定义,函数定义时自带两个参数navigation和screenProps。其中navigation主要是路由传参内容,screenProps主要是在定义router的时候带着的参数,一会再把navigationOptions的具体属性补充一下TODO

header怎么和app中通信呢?

小白踩坑后知道navigationOptions中是不能直接访问reactComponent中的this对象的,因此也就不能直接和reactComponent进行通信,这个时候怎么办呢?答案就是操作navigation对象,我们可以通过在组件中重新定义navigation参数params的形式来处理,比如

代码语言:javascript
复制
static navigationOptions = ({ navigation, screenProps }) => {
  return {
    headerTintColor:'#000',
    headerTitle: (
      <Text style={{ flex: 1, textAlign: 'center', color: '#222222', fontSize: px2dp(18) }}>网络日志</Text>
    ),
    // 这里之所以要判断 是因为在生命周期最开始的时候 这个params我们还没给他绑定点击事件
    headerRight: <View><Text onPress={navigation.state.params?navigation.state.params.navigatePress:null}>清空</Text></View>
  }
}
componentDidMount() {
  this.props.navigation.setParams({
    navigatePress:this._clearStorage
  })
}
_clearStorage = () => {
  global.storage.remove({
    key:'netLog'
  }).then((logs) => {
    console.log('data removed')
    this.setState(previousState => {
      return {
        logList: []
      }
    })
  })
}

而在组件中去调用头部的内容时,也是主要去查询navigation这个对象中的state和params两个参数,先到这 上个厕所

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-11-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 基本使用(此处基本使用仅针对导航头部而言,不包含tabbar等)
    • 组件引入与定义路由
      • 自定义header内容
      • header怎么和app中通信呢?
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档