React Native使用自定义组件添加顶部导航栏

源码

/*
 * @Author: YooHoeh 
 * @Date: 2018-07-11 21:25:31 
 * @Last Modified by: YooHoeh
 * @Last Modified time: 2018-07-12 08:37:32
 */

import React, { Component, PropTypes } from "react";
import { View, Text, StyleSheet, Platform, StatusBar, } from "react-native";
import { platform } from "os";

const NAV_BAR_HEIGHT_ANDROID = 50;
const NAV_BAR_HEIGHT_IOS = 44;
// ios状态栏高度
const STATUS_BAR_HEIGHT = 20;
const statusBarShape={
  backgroundColor:PropTypes.string,
  barStyle:PropTypes.oneOf('default','light-content','dark-content'),
  hidden:PropTypes.bool,
}  

export default class NavigationBar extends Component {
  // 自定义组件并对其设置属性限定
  static propTypes = {
    style: View.propTypes.style,
    title: PropTyoes.string,
    titleView: PropTypes.element,
    hide: PropTypes.bool,
    leftButton: PropTypes.element,
    rightButton: PropTypes.element,
    statusBar:PropTypes.shap(statusBarShape)
  };
  // 组件默认设置
  static defaultProps={
    statusBar:{
      barStyle:'light-content',
      hidden:false,
    }
  }
  // 构造函数,默认导航栏不隐藏
  constructor(props) {
    super(props);
    this.state = {
      title: "",
      hide: false
    };
  }
  render() {
    // 状态栏
    let status = <View style={[styles.statusBar,this.props.statusBar]}>
      <StatusBar {...this.props.statusBar}/>
    </View>;
    // 判断标题是字符串还是一个view组件
    let titleView = this.props.titleView ? (
      this.props.titleView
    ) : (
      <Text style={styles.title}>{this.props.title}</Text>
    );
    let content = (
      <View style={styles.navBar}>
        {this.props.leftButton}
        <View style={styles.titleViewContainer}>{titleView}</View>
        {this.props.rightButton}
      </View>
    );

    return <View style={[StyleSheet.container,this.props.style]}>
      {status}
      {content}
    </View>;
  }
}

// 样式
const styles = StyleSheet.create({
  container: {
    backgroundColor: "grey"
  },
  navBar: {
    justifyContent: "space-between",
    alignItem: "center",
    height: Platform.OS === "ios" ? NAV_BAR_HEIGHT_IOS : NAV_BAR_HEIGHT_ANDROID,
    flexDirection: "row"
  },
  titleViewContainer: {
    justifyContent: "center",
    alignItem: "center",
    positon: "absolute",
    left: 40,
    right: 40,
    top: 0,
    bottom: 0
  },
  title: {
    fontSize: 20,
    color: "white"
  },
  statusBar: {
    height: Platform.OS === "ios" ? STATUS_BAR_HEIGHT : 0
  }
});
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页