hcmobile-sdk
Version:
mobile-sdk
149 lines (135 loc) • 3.9 kB
JavaScript
import React, {Component} from 'react';
import {
StyleSheet,
View,
Image,
Text,
TouchableHighlight,
} from 'react-native'
import PropTypes from 'prop-types';
export default class SelectButton extends Component {
constructor(props) {
super(props);
this.state = {
checkState: this.props.defaultChecked || false,
keyValue: this.props.keyValue,
}
}
/**
* 类型校验
*
*/
static propTypes = {
keyValue: PropTypes.string,
leftText: PropTypes.string,
leftTextView: PropTypes.element,
rightText: PropTypes.string,
leftTextStyle: PropTypes.object,
rightTextView: PropTypes.element,
rightTextStyle: PropTypes.object,
checkedColor: PropTypes.string,
unCheckedColor: PropTypes.string,
checkedImage: PropTypes.element,
unCheckedImage: PropTypes.element,
onClick: PropTypes.func,
setChecked: PropTypes.bool,
defaultChecked: PropTypes.bool,
};
/**
* 默认
*/
static defaultProps = {
defaultChecked: false,
leftTextStyle: {},
rightTextStyle: {}
};
/**
* 左边的文字
*/
_renderLeft(fontColor) {
if (this.props.leftTextView) {
return this.props.leftTextView;
}
if (!this.props.leftText) {
return null;
}
return (
<Text style={[styles.leftText, {color: fontColor}, this.props.leftTextStyle]}>{this.props.leftText}</Text>
)
}
/**
* 右边的文字
*/
_renderRight(fontColor) {
if (this.props.rightTextView) {
return this.props.rightTextView;
}
if (!this.props.rightText) {
return null;
}
return (
<Text
style={[styles.rightText, {color: fontColor}, this.props.rightTextStyle]}>{this.props.rightText}</Text>
)
}
/**
* 选中和未选中的图片按钮样式
*/
_renderImage() {
if (this.state.checkState) {
return this.props.checkedImage ? this.props.checkedImage : null;
} else {
return this.props.unCheckedImage ? this.props.unCheckedImage : null;
}
}
onClick() {
this.setState({
checkState: !this.state.checkState
});
this.props.onClick(this.state.keyValue);
}
render() {
if (this.props.setChecked !== undefined) {
this.state.checkState = this.props.setChecked;
}
let borderColor = 'transparent';
let fontColor = 'black';
if (!(this.props.unCheckedImage && this.props.checkedImage)) {
if (this.props.checkedColor && this.props.unCheckedColor) {
borderColor = this.state.checkState ? this.props.checkedColor : this.props.unCheckedColor;
fontColor = borderColor;
} else {
borderColor = this.state.checkState ? 'crimson' : 'grey';
fontColor = borderColor;
}
}
return (
<TouchableHighlight
onPress={() => this.onClick()}
underlayColor='transparent'>
<View
style={[styles.container, this.props.style, {borderColor: borderColor}]}>
{this._renderLeft(fontColor)}
{this._renderImage()}
{this._renderRight(fontColor)}
</View>
</TouchableHighlight>
)
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
borderWidth: 1,
borderRadius: 3,
},
leftText: {
fontSize: 14,
margin: 5,
},
rightText: {
fontSize: 14,
margin: 5,
}
});