说按钮其实有点不妥,react native提供了四个组件让包裹在里面的东西能拥有可点击的能力。
- TouchableHighlight
- TouchableNativeFeedback
- TouchableOpacity
- TouchableWithoutFeedback
不过我建议直接使用最后一个。如果大家想与原生的一致,就用第二个。反正TouchableHighlight与TouchableOpacity都能通过其事件实现的。
2)React按钮的事件处理 按钮关联了四个事件:
1. 按钮按下事件:onPress - 按下并松开按钮,会触发该事件(相当于PC的onclick) 2. 按钮长按事件:onLongPress - 按住按钮不松开,会触发该事件(长按事件) 3. 按钮按下事件:onPressIn - 按下按钮不松开,会触发该事件(相当于PC的onkeydown) 4. 按钮松开事件:onPressOut - 按下按钮后松开,或按下按钮后移动手指到按钮区域外,都会触发该事件(相当于PC的onkeyup)
/**
* button by 司徒正美
*/
'use strict';
var React = require('react-native');
var {
AppRegistry,
TouchableWithoutFeedback,
StyleSheet,
Text,
View,
} = React;
var Button = React.createClass({
getInitialState(){
return {
active: false
}
},
onkeyDown() {
this.setState({active: true})
},
onkeyUp() {
this.setState({active: false})
},
render() {
return (
<View style={{marginTop: 20}}>
<TouchableWithoutFeedback
onPressIn={this.onkeyDown}
onPressOut={this.onkeyUp}
>
<View style={[styles.button, this.state.active ? styles.activeButton: {} ]}>
<Text style={[styles.buttonText, this.state.active ? styles.activeText: {}]}>Button</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
}
});
var styles = StyleSheet.create({
button:{
flex:1,
flexDirection:'row',
justifyContent: 'center',
alignItems:'center',
width: 200,
height: 50,
borderColor:'#00afc7',
borderWidth:1,
borderRadius:5,
backgroundColor: 'white',
shadowColor: "#57c6fa",
shadowOffset: {width: 2, height: 2},
shadowOpacity:0.5,
shadowRadius:5,
},
buttonText: {
padding:5,
color:"#00afc7",
},
activeButton: {
backgroundColor:"#00afc7",
},
activeText:{
color:"fff",
fontWeight:'bold',
}
});
AppRegistry.registerComponent('AwesomeProject', () => Button);