您的位置:首页 > Web前端 > React

react native button 按钮

2016-11-26 22:29 239 查看

用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,
StyleSheet,
Text,
View,
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,
}
});






内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: