在RN中並沒有onclick監聽,想要在組件中註冊點擊事件,需要使用Touchable。該組件也可以理解爲一個Animated.View容器,然後把需要註冊點擊事件的組件作爲子組件,並註冊onPress函數實現點擊效果。
Touchable目前有三種效果:
- TouchableHighlight:點擊時顯示高亮效果
- TouchableOpacity:點擊時顯示半透明效果
- TouchableWithoutFeedback:無效果
Touchable屬性:
屬性 | 描述 |
---|---|
style |
顯示樣式 |
onPress |
註冊點擊(觸摸)事件函數 |
onPressIn |
按下時觸發的函數 |
onPressOut |
鬆開時觸發的函數 |
onLongPress |
長按時觸發的函數 |
delayLongPress |
設置觸發onLongPress事件所需要的長按時間,單位毫秒 |
activeOpacity |
範圍0~1,表示觸摸時顯示的透明度,TouchableHighlight默認爲0.85;TouchableOpacity默認爲0.2 |
underlayColor |
僅TouchableHighlight有效,表示觸摸操作時組件的背景色 |
貼上代碼:
import React, { Component } from 'react';
import {
View,
StyleSheet,
Text,
TouchableHighlight,
TouchableOpacity
} from 'react-native';
class TouchableComp extends Component {
_onPress = () => {
console.log('onPress');
}
_onPressOut = () => {
console.log('onPressOut');
}
_onPressIn = () => {
console.log('onPressIn');
}
_onLongPress = () => {
console.log('onLongPress');
}
render() {
return (
<View>
<TouchableHighlight
style={styles.buttonStyle}
onPress={this._onPress}
onPressIn={this._onPressIn}
onPressOut={this._onPressOut}
onLongPress={this._onLongPress}
activeOpacity={0.85}
delayLongPress={3800}
underlayColor='green'
>
<Text style={styles.textStyle}>TouchableHighlight</Text>
</TouchableHighlight>
<TouchableOpacity
style={styles.buttonStyle}
onPress={this._onPress}
onPressIn={this._onPressIn}
onPressOut={this._onPressOut}
onLongPress={this._onLongPress}
delayLongPress={3800}
activeOpacity={0.2}
>
<Text style={styles.textStyle}>TouchableOpacity</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
buttonStyle:{
justifyContent: 'center',
borderColor: '#000000',
backgroundColor: '#DDDDDD',
borderWidth: 1,
borderRadius: 10,
margin: 20,
height: 50
},
textStyle:{
fontSize: 16,
color: '#000000',
alignSelf: 'center'
}
});
export default TouchableComp;
效果: