React Native组件学习之设置动态参数
###NavBar.js
import React, {Component,} from 'react'
import {
StyleSheet,
View,
Animated,
TouchableOpacity,
TouchableNativeFeedback,
Platform
} from 'react-native'
import px2dp from './px2dp'
import Icon from 'react-native-vector-icons/Ionicons'
const PropTypes = require('prop-types');
export default class NavBar extends Component {
static propTypes = { //接收以下六个参数:
title: PropTypes.string, //标题
leftIcon: PropTypes.string, //左边图标
rightIcon: PropTypes.string, //右边图标
leftPress: PropTypes.func, //左边点击事件方法
rightPress: PropTypes.func, //右边点击事件方法
style: PropTypes.object //style样式
}
static topbarHeight = (Platform.OS === 'ios' ? 64 : 42)
renderBtn(pos) {
let render = (obj) => {
const {name, onPress} = obj;
if (Platform.OS === 'android') {
return (
<TouchableNativeFeedback onPress={onPress} style={styles.btn}>
<Icon name={name} size={px2dp(26)} color="#fff"/>
</TouchableNativeFeedback>
)
} else {
return (
<TouchableOpacity onPress={onPress} style={styles.btn}>
<Icon name={name} size={px2dp(26)} color="#fff"/>
</TouchableOpacity>
)
}
}
if (pos == "left") {
if (this.props.leftIcon) {
return render({
name: this.props.leftIcon,
onPress: this.props.leftPress
})
} else {
return (<View style={styles.btn}></View>)
}
} else if (pos == "right") {
if (this.props.rightIcon) {
return render({
name: this.props.rightIcon,
onPress: this.props.rightPress
})
} else {
return (<View style={styles.btn}></View>)
}
}
}
render() {
return (
<View style={[styles.topbar, this.props.style]}>
{this.renderBtn("left")}
<Animated.Text numberOfLines={1}
style={[styles.title, this.props.titleStyle]}>{this.props.title}</Animated.Text>
{this.renderBtn("right")}
</View>
)
}
}
const styles = StyleSheet.create({
topbar: {
height: NavBar.topbarHeight,
backgroundColor: "#1E82D2",
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingTop: (Platform.OS === 'ios') ? 20 : 0,
paddingHorizontal: px2dp(10)
},
btn: {
width: 40,
height: 40,
justifyContent: 'center',
alignItems: 'center'
},
title: {
color: "#fff",
fontWeight: "bold",
fontSize: px2dp(16),
marginLeft: px2dp(5),
}
});
####px2dp.js
import {Dimensions} from 'react-native'
const deviceW = Dimensions.get('window').width
const basePx = 375
export default function px2dp(px) {
return px * deviceW / basePx;
}
那么我们在调用NavBar组件时只需要传入title、leftIcon、leftPress、rightIcon和rightPress就可以了:
<NavBar
title="我的"
leftIcon="ios-notifications-outline"
leftPress={this.leftPress.bind(this)}
rightIcon="ios-settings-outline"
rightPress={this.rightPress.bind(this)}/>
js
<NavBar
title="新闻"
titleStyle={styles.titleStyle}
style={styles.style}/>
css
style: {
height: NavBar.topbarHeight,
backgroundColor: "#fff",
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingTop: (Platform.OS === 'ios') ? 20 : 0,
paddingHorizontal: px2dp(10)
},
titleStyle: {
fontSize: 16,
color: '#000',
fontWeight: "bold",
}
注意style的命名一定要跟上面this.props后面的参数一致!
还没有评论,来说两句吧...