1 觸摸事件
普通點選我們可以使用onPress方法,我們可以使用Touchable 系列控件設計我們的按鈕
TouchableHighlight 背景會在使用者手指按下時變暗
TouchableNativeFeedback使用者手指按下時形成類似墨水漣漪的視覺效果
TouchableOpacity指按下時降低按鈕的透明度,而不會改變背景的顔色
TouchableWithoutFeedback 不顯示任何視覺回報
檢測使用者是否進行了長按操作,可以在上面列出的任意元件中使用onLongPress屬性來實作
2 測試關鍵代碼如下
要記得導入相應的元件
import React, {Component} from 'react';
import {Platform, ScrollView, StyleSheet, Text, View, TextInput, NativeModules, DeviceEventEmitter, Image, Button, AppRegistry, TouchableHighlight, TouchableOpacity, TouchableNativeFeedback, TouchableWithoutFeedback} from 'react-native';
export default class App extends Component<Props> {
render() {
return (
<View style={styles.container}>
<View style={styles.buttonContainer}>
<Button onPress={this.showMsg} title="press me"/>
</View>
<View style={styles.buttonContainer}>
<Button onPress={this.showMsg} title="press me" color="#841584"/>
</View>
<View style={styles.buttonContainer}>
<TouchableHighlight onPress={this.showMsg} underlayColor="white">
<View style={styles.button}>
<Text style={styles.text}>TouchableHighlight</Text>
</View>
</TouchableHighlight>
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity onPress={this.showMsg}>
<View style={styles.button}>
<Text style={styles.text}>TouchableOpacity</Text>
</View>
</TouchableOpacity>
</View>
<View style={styles.buttonContainer}>
<TouchableNativeFeedback onPress={this.showMsg}>
<View style={styles.button}>
<Text style={styles.text}>TouchableNativeFeedback</Text>
</View>
</TouchableNativeFeedback>
</View>
<View style={styles.buttonContainer}>
<TouchableWithoutFeedback onPress={this.showMsg}>
<View style={styles.button}>
<Text style={styles.text}>TouchableWithoutFeedback</Text>
</View>
</TouchableWithoutFeedback>
</View>
<View style={styles.buttonContainer}>
<TouchableWithoutFeedback onLongPress={this.showMsg}>
<View style={styles.button}>
<Text style={styles.text}>onLongPress me</Text>
</View>
</TouchableWithoutFeedback>
</View>
<View style={styles.layoutButtonContainer}>
<Button onPress={this.showMsg} title="onLongPress me"/>
<Button onPress={this.showMsg} title="onLongPress me" color="#841584"/>
</View>
</View>
);
}
//記得這裡調用的時候不需要加上()
showMsg(){
alert("showMsg(){}");
}
//記得末尾加上分号,調用的時候也要加上()
showMessage = () => {
alert("showMessage = () => {}");
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center'
},
buttonContainer: {
margin:10
},
layoutButtonContainer: {
margin:10,
flexDirection: 'row',
justifyContent: 'space-between'
},
button: {
alignItems: 'center',
backgroundColor: '#842534'
},
text: {
padding: 10,
color: 'white'
}
});