本文基於React Native 0.52
Demo上傳到Git了,有需要可以看看,寫了新內容會上傳的。Git地址 https://github.com/gingerJY/React-Native-Demo
一、總覽
頭部通常分為左、中、右三部分,效果圖如下:
二、頭部組件
1、創建components文件夾,新建commonHead.js
2、commonHead.js
頭部分為左、中、右三塊,我們需要提供接口,獲取外部傳入的值,從而判斷哪一塊需要創建。
static propTypes = { leftItem: PropTypes.func, titleItem: PropTypes.func, rightItem: PropTypes.func, };
左側模塊(中和右一樣)
renderLeftItem(){ if (this.props.leftItem === undefined) return; return this.props.leftItem(); }
樣式,設置了一些默認樣式和布局,也可以通過 navBarStyle 添加樣式或是覆蓋默認樣式
render() { return ( <View style={[{width:width, height:40, backgroundColor: this.props.navBarColor || '#fff',//背景色,默認白色 flexDirection:'row',//橫向排 justifyContent:'space-between',//主軸對齊方式 alignItems: 'center',//次軸對齊方式(上下居中) borderBottomWidth: this.props.borderBottomWidth || 0,//是否有下邊框 borderColor: this.props.borderColor || '#ccc', }, this.props.navBarStyle,]}> <View> {this.renderLeftItem()} </View> <View> {this.renderTitleItem()} </View> <View> {this.renderRightItem()} </View> </View> ); }
commonHead.js完整代碼 https://github.com/gingerJY/example/blob/master/RN_commonHead/commonHead.js
三、使用組件
1、在home.js中引入頭部組件
import CommonHead from '../../components/commonHead';
2、寫左中右三部分
// 頭部左側 renderLeftItem() { return ( <TouchableOpacity onPress={() => { this.props.navigation.navigate('Search') }} style={styles.navLeft}> <Image source={require('../../img/scanning.png')} style={styles.navIcon} /> <Text style={styles.navText}>掃一掃</Text> </TouchableOpacity> ) } // 頭部中間 renderTitleItem() { return ( <TouchableOpacity onPress={() => { this.props.navigation.navigate('Search') }}> <View style={styles.searchBox}> <Image source={require('../../img/search.png')} style={styles.searchIcon} /> <Text style={styles.searchContent}>搜索商品, 共10161款好物</Text> </View> </TouchableOpacity> ) } // 頭部右側 renderRightItem() { return ( <TouchableOpacity onPress={() => { this.props.navigation.navigate('MessageCenter') }} style={styles.navRight}> <Image source={require('../../img/remind.png')} style={styles.navIcon} /> <Text style={styles.navText}>消息</Text> </TouchableOpacity> ) }
3、使用commonHead
<CommonHead leftItem={() => this.renderLeftItem()} titleItem={() => this.renderTitleItem()} rightItem={() => this.renderRightItem()} />
home.js完整代碼 https://github.com/gingerJY/example/blob/master/RN_commonHead/home.js
注:上面的代碼有些內容,如樣式等沒有寫到,點鏈接可以看到完整代碼,文章開頭那個git地址是整個項目的代碼。
另:圖標來自 http://www.iconfont.cn/
END---------------------------------------------------------------
上有天堂,下有書房。