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'}}
/>
- 實現效果
普通狀態.png
高亮狀態.png