ReactNative之自定义高亮按钮
- 在RN开发中,自带的按钮组件非常不好用,没有高亮状态,更加不可以自定义样式,要达到开发需求只能自定义按钮了。
自定义高亮按钮
static propTypes = {
// 普通状态
title:PropTypes.string,
imageUri:PropTypes.string,
titleStyle:PropTypes.object,
imageStyle:PropTypes.object,
// 高亮状态
highImageUri:PropTypes.string,
highTitleStyle:PropTypes.object,
// 监听点击
onPressIn:PropTypes.func,
onPressOut:PropTypes.func,
// 按钮样式
buttonStyle:PropTypes.object
};
/**
* Created by ithinkeryz on 2017/5/16.
*/
/**
* Created by ithinkeryz on 2017/5/15.
*/
import React, { Component,PropTypes} from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TouchableOpacity
} from 'react-native';
export default class CommonHighButtonButton extends Component {
static propTypes = {
// 普通状态
title:PropTypes.string,
imageUri:PropTypes.string,
titleStyle:PropTypes.object,
imageStyle:PropTypes.object,
// 高亮状态
highImageUri:PropTypes.string,
highTitleStyle:PropTypes.object,
// 监听点击
onPressIn:PropTypes.func,
onPressOut:PropTypes.func,
// 按钮样式
buttonStyle:PropTypes.object
};
constructor(props){
super(props);
this.state = {
highLighted:false
}
}
render() {
return (
<TouchableOpacity style={[styles.buttonStyle,this.props.buttonStyle]}
onPressIn={()=>{
this.setState({
highLighted:true
});
if (this.props.onPressIn){
this.props.onPressIn(this);
}
}}
onPressOut={()=>{
this.setState({
highLighted:false
});
if (this.props.onPressOut){
this.props.onPressOut(this);
}
}
}
activeOpacity={this.props.highTitleStyle || this.props.highImageUri?0.9:0.3}
>
{/*文字*/}
{this.props.title?<Text style={[this.props.titleStyle,this.state.highLighted?this.props.highTitleStyle:null]}>{this.props.title}</Text>:null}
{/*头像*/}
{this.props.imageUri?<Image source={{uri:this.state.highLighted && this.props.highImageUri?this.props.highImageUri:this.props.imageUri}} style={[styles.imageStyle,this.props.imageStyle]}/> : null}
</TouchableOpacity>
);
}
}
var styles = StyleSheet.create({
buttonStyle:{
backgroundColor:'white',
flexDirection:'row',
justifyContent:'center',
alignItems:'center'
},
imageStyle:{
marginLeft:3
}
});
<CommonHighButton imageUri='nav_item_game_icon'
imageStyle={{width:20,height:20}}
title='按钮'
highImageUri='nav_item_game_click_icon'
highTitleStyle={{color:'red'}}
/>