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

目录

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


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

基础使用主要包括两部分

组件引入与定义路由

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

import { createStackNavigator } from 'react-navigation';
export default createStackNavigator({
  Home: {
    screen: App
  },
  Demos: {
    screen: demo
  },
  DebugList: DebugList,
  DebugDetail: DebugDetail
})

自定义header内容

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

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的形式来处理,比如

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两个参数,先到这 上个厕所

猜你喜欢

转载自www.cnblogs.com/heioray/p/9956737.html