React Native 中 React Navigation 导航器使用详解

Viewed 0

React Navigation 是 React Native 应用中常用的导航库,主要提供三种导航器:StackNavigator、TabNavigator 和 DrawerNavigator。

  • StackNavigator:提供屏幕上方导航栏,类似于普通导航器。
  • TabNavigator:实现屏幕下方的标签栏,类似 iOS 的 TabBarController。
  • DrawerNavigator:支持抽屉效果,可从侧边滑出。

使用 React Navigation 的第一步是新建 React Native 项目并安装库。通过 react-native init ComponentDemo 创建项目,然后运行 npm install --save react-navigation 进行安装。

TabNavigator 非常适合实现底部标签栏布局,例如首页包含多个标签页的情况。以下是一个 TabNavigator 的配置示例,定义了两个标签页“Home”和“Certificate”,并设置了图标、样式等选项:

import {StackNavigator, TabNavigator} from "react-navigation";

const MainScreenNavigator = TabNavigator({
  Home: {
    screen: Home,
    navigationOptions: {
      tabBar: {
        label: '互助',
        icon: ({tintColor}) => (
          <Image
            source={require('../images/home.png')}
            style={[{tintColor: tintColor},styles.icon]}
          />
        ),
      },
    }
  },
  Certificate: {
    screen: Certificate,
    navigationOptions: {
      tabBar: {
        label: '凭证',
        icon: ({tintColor}) => (
          <Image
            source={require('../images/cert.png')}
            style={[{tintColor: tintColor},styles.icon]}
          />
        ),
      },
    }
  },
}, {
  animationEnabled: false,
  tabBarPosition: 'bottom',
  swipeEnabled: false,
  backBehavior: 'none',
  tabBarOptions: {
    activeTintColor: '#0F9C00',
    inactiveTintColor: '#999',
    showIcon: true,
    indicatorStyle: {height: 0},
    style: {
      backgroundColor: '#fff',
    },
    labelStyle: {
      fontSize: 12,
    },
  },
});

const styles = StyleSheet.create({
  icon: {
    height: 22,
    width: 22,
    resizeMode: 'contain'
  }
});

然后,可以使用 StackNavigator 将 TabNavigator 作为首页,并添加其他页面以实现导航。StackNavigator 和 TabNavigator 可以相互嵌套,从而支持从首页标签页跳转到其他页面。以下是一个 StackNavigator 的示例,将上述 TabNavigator 作为主屏幕,并添加一个详情页面:

const App = StackNavigator({
  Main: {
    screen: MainScreenNavigator,
    navigationOptions: {
      header: {
        title: '互助',
        style: {
          backgroundColor: '#fff'
        },
        backTitle: null
      }
    }
  },
  PlanDetail: {
    screen: PlanDetail,
    navigationOptions: {
      header: {
        style: {
          backgroundColor: '#fff'
        },
      }
    }
  }
},{
  mode: 'card',
  headerMode: 'none',
});

在页面中,可以使用 navigate 函数进行跳转并传递参数。例如:

const {navigate} = this.props.navigation;
<TouchableHighlight onPress={()=>{
  navigate('PlanDetail',{name:'leslie',id:100});
}}>

返回上一页可以使用 goBack 方法:

this.props.navigation.goBack();

接收参数时,在目标页面中通过 this.props.navigation.state.params 访问:

export default class PlanDetail extends Component {
  static navigationOptions = {
    title: ({state}) => `${state.params.name}`,
  };
  componentDidMount() {
    const {params} = this.props.navigation.state;
    const id = params.id;
  }
}

通过以上配置和代码,可以快速在 React Native 应用中实现复杂的导航结构。

0 Answers