用react native自定义一个button按钮
button代码,响应按下事件,设置获取disabled状态,设置获取显示文本
import React,{ Component } from 'react';
import {
AppRegistry,StyleSheet,Text,View,TouchableOpacity
} from 'react-native';
export default class Button extends Component {
constructor(props) {
super(props);
this.state = {
disabled: props.disabled,text: props.text,}
}
onPress_() {
if (typeof this.props.onPress === 'function') {
this.props.onPress();
}
}
setDisabled_(yes) { this.setState({disabled: yes}); }
isDisabled_() { return this.state.disabled; }
setText_(text) { this.setState({text: text}); }
text_() { return this.state.text; }
render() {
return (
<TouchableOpacity
style={[styles.button,this.state.disabled && styles.disabled]}
onPress={this.onPress_.bind(this)}
disabled={this.state.disabled} >
<Text style={styles.text}>
{this.state.text}
</Text>
</TouchableOpacity>
)
}
}
styles = StyleSheet.create({
button: {
backgroundColor:'#0c3ba9',width: 80,height: 40,justifyContent: 'center',borderRadius: 10,overflow: 'hidden',},text: {
textAlign: 'center',color: '#fff',fontSize: 16,disabled: {
backgroundColor: '#999999'
}
})
测试代码
import React,{ Component } from 'react';
import {
AppRegistry,TextInput
} from 'react-native';
import Button from '../common/Button.js'
export default class ButtonTest extends Component {
onToggle_() {
this.refs.okButton.setDisabled_(!this.refs.okButton.isDisabled_());
}
render() {
return (
<View style={styles.container}>
<Button ref="okButton" text="确定" onPress={()=>{alert(this.refs.okButton.text_())}} />
<Button text="切换状态" onPress={this.onToggle_.bind(this)} />
<TextInput style={styles.textInput} placeholder="改变确定按钮文本" onChangeText={(text) => this.refs.okButton.setText_(text)} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,flexDirection: 'row',justifyContent: 'space-around',alignItems: 'center',backgroundColor: '#F5FCFF',textInput: {
width: 130,}
});