本文基于React Native 0.52

Demo上传到Git了,有需要可以看看,写了新内容会上传的。Git地址 https://github.com/gingerJY/React-Native-Demo

  头部通常分为左、中、右三部分,效果图如下:

 

  1、创建components文件夹,新建commonHead.js

  2、commonHead.js

头部分为左、中、右三块,我们需要提供接口,获取外部传入的值,从而判断哪一块需要创建。

  1. static propTypes = {
  2. leftItem: PropTypes.func,
  3. titleItem: PropTypes.func,
  4. rightItem: PropTypes.func,
  5. };

  左侧模块(中和右一样)

  1. renderLeftItem(){
  2. if (this.props.leftItem === undefined) return;
  3. return this.props.leftItem();
  4. }

  样式,设置了一些默认样式和布局,也可以通过 navBarStyle 添加样式或是覆盖默认样式

  1. render() {
  2. return (
  3. <View style={[{width:width,
  4. height:40,
  5. backgroundColor: this.props.navBarColor || '#fff',//背景色,默认白色
  6. flexDirection:'row',//横向排
  7. justifyContent:'space-between',//主轴对齐方式
  8. alignItems: 'center',//次轴对齐方式(上下居中)
  9. borderBottomWidth: this.props.borderBottomWidth || 0,//是否有下边框
  10. borderColor: this.props.borderColor || '#ccc',
  11. }, this.props.navBarStyle,]}>
  12. <View>
  13. {this.renderLeftItem()}
  14. </View>
  15. <View>
  16. {this.renderTitleItem()}
  17. </View>
  18. <View>
  19. {this.renderRightItem()}
  20. </View>
  21. </View>
  22. );
  23. }

  commonHead.js完整代码 https://github.com/gingerJY/example/blob/master/RN_commonHead/commonHead.js

  1、在home.js中引入头部组件

  1. import CommonHead from '../../components/commonHead';

  2、写左中右三部分

  1. // 头部左侧
  2. renderLeftItem() {
  3. return (
  4. <TouchableOpacity onPress={() => { this.props.navigation.navigate('Search') }} style={styles.navLeft}>
  5. <Image source={require('../../img/scanning.png')} style={styles.navIcon} />
  6. <Text style={styles.navText}>扫一扫</Text>
  7. </TouchableOpacity>
  8. )
  9. }
  10. // 头部中间
  11. renderTitleItem() {
  12. return (
  13. <TouchableOpacity onPress={() => { this.props.navigation.navigate('Search') }}>
  14. <View style={styles.searchBox}>
  15. <Image source={require('../../img/search.png')} style={styles.searchIcon} />
  16. <Text style={styles.searchContent}>搜索商品, 10161款好物</Text>
  17. </View>
  18. </TouchableOpacity>
  19. )
  20. }
  21. // 头部右侧
  22. renderRightItem() {
  23. return (
  24. <TouchableOpacity onPress={() => { this.props.navigation.navigate('MessageCenter') }} style={styles.navRight}>
  25. <Image source={require('../../img/remind.png')} style={styles.navIcon} />
  26. <Text style={styles.navText}>消息</Text>
  27. </TouchableOpacity>
  28. )
  29. }

  3、使用commonHead

  1. <CommonHead
  2. leftItem={() => this.renderLeftItem()}
  3. titleItem={() => this.renderTitleItem()}
  4. rightItem={() => this.renderRightItem()}
  5. />

     home.js完整代码 https://github.com/gingerJY/example/blob/master/RN_commonHead/home.js

 

注:上面的代码有些内容,如样式等没有写到,点链接可以看到完整代码,文章开头那个git地址是整个项目的代码。

另:图标来自 http://www.iconfont.cn/

 

END—————————————————————  

上有天堂,下有书房。

 

版权声明:本文为MaiJiangDou原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/MaiJiangDou/p/8329984.html