react native实现按钮有4种方式,官方提供的原生TouchableOpacity,TouchableHighlight,TouchableWithoutFeedback,以及第三方封装的按钮
其中原生TouchableOpacity最为常用,TouchableHighlight自带的点击变色效果不够友好,TouchableWithoutFeedback官方不推荐使用。
注意:TouchableOpacity、TouchableHighlight只能有一个子控件,如果有多个要用View包起来。
这里主要讲解TouchableOpacity的实现方法
废话少说先上代码:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TouchableOpacity,
TouchableHighlight
} from 'react-native';
export default class FirstApp extends Component {
constructor(props) {
super(props);
this.state = {code:1,msg:"测试"};
}
showAlert=()=>{
//使用箭头函数才能用this
alert(JSON.stringify(this.state));
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity style={styles.button} onPress={this.showAlert}>
<Text style={styles.buttonText}>按钮</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
button:{
width:100,
height:40,
borderRadius:10,
backgroundColor:"green",
justifyContent:'center',
},
buttonText:{
textAlign:"center",
color:"white"
}
});
AppRegistry.registerComponent('FirstApp', () => FirstApp);
解释:
第13行showAlert() 是点击按钮执行的方法,此处要用函数表达式,或者箭头函数,不要用声明函数的方法,否则在方法里面不能调用this
第20行 onPress={this.showAlert},是绑定按钮点击事件,注意showAlert后面不要带括号,如果写成 onPress={this.showAlert()}启动后自动调用该方法
40行justifyContent:’center’表示垂直居中
感谢:
http://reactnative.cn/docs/0.48/tutorial.html#content
http://blog.csdn.net/bboyklc/article/details/50827969