首先创建自定义组件js文件,然后导入NavigationBar需要的的组件,给组件定义属性,为了规范调用者的使用,可以给属性进行类型检查,,如果某些属性为用户必须设置,,给属性设置默认值,最后在render方法中返回渲染、设置样式以及判断Android、ios平台。
导入prop-types
过去我们可以通过React.PropTyoes来进行属性确认,不过这个自React v15.5起就被移除了,现在我们通过prop-types库来进行属性确认。
(1)安装 prop-types 库:
yarn add prop-types
(2) 在需要使用的 js 文件中使用如下代码引入:
import PropTypes from 'prop-types'
定义一些常量
const NAV_BAR_HEIGHT_ANDROID=50; //Android的NavigationBar高度
const NAV_BAR_HEIGHT_IOS = 44; //iOs的NavigationBar高度
const STATUS_BAR_HEIGHT=20; //状态栏高度
const StatusBarShape={ //状态栏形状的约束,用来属性确认
backgroundColor:PropTypes.string,
barStyle:PropTypes.oneOf('default' , 'light-content' , 'dark-content'),
hidden:PropTypes.bool,
}
定义属性约束
static propTypes = {
style: PropTypes.object, //NavigationBar样式约束
title: PropTypes.string, //标题约束:文本类标题
titleView:PropTypes.element, //标题的样式约束
hide:PropTypes.bool, //是否隐藏NavigationBar
leftButton:PropTypes.element, //NavigationBar左侧按钮
rightButton:PropTypes.element, //NavigationBar右侧按钮
staturBar: PropTypes.shape(StatusBarShape), //状态栏
};
给某些属性设置默认值
static defaultProps ={
staturBar:{
barStyle: 'light-content',
hidden:false,
}
}
constructor(props){
super(props);
this.state ={
title:' ',
hide:false,
};
}
在render()方法中返回渲染
render(){
let status = <View style={[styles.staturBar , this.props.staturBar]}> //获取用户设置的状态栏的样式,用于下面的取出
<StatusBar {...this.props.staturBar}/> //取出用户设置的状态栏的样式
</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}>
{status}
{titleView}
</View>
{this.props.rightButton}
</View>;
return(
<View style={styles.container}>
{content}
</View>
)
}
}
渲染的样式
const styles = StyleSheet.create({
container:{
backgroundColor:'gray',
},
navBar:{
flexDirection: 'row',
justifyContent:'space-between',
alignItems: 'center',
height:Promise.OS === 'ios'? NAV_BAR_HEIGHT_IOS:NAV_BAR_HEIGHT_ANDROID,
backgroundColor: '#2196F3',
},
titleViewContainer:{
justifyContent: 'center',
alignItems: 'center',
position:'absolute',
left:40,
right:40,
top:0,
bottom:0,
},
title:{
fontSize:20,
color:'white'
},
staturBar:{
height:Platform.OS==='ios'?STATUS_BAR_HEIGHT:0,
}
});
使用
<NavigationBar
title='最新'
statusBar={{
backgroundColor:'#2196F3'
}}
/>
leftButton
和rightButton
就留给你们自己尝试一下吧
下面就贴出效果图了