React Native之觸摸事件(Touchable系列和onLongPress)
1 觸摸事件
普通點擊我們可以使用onPress方法,我們可以使用Touchable 系列控件設計我們的按鈕
TouchableHighlight 背景會在用戶手指按下時變暗
TouchableNativeFeedback用戶手指按下時形成類似墨水漣漪的視覺效果
TouchableOpacity指按下時降低按鈕的透明度,而不會改變背景的顏色
TouchableWithoutFeedback 不顯示任何視覺反饋
檢測用戶是否進行了長按操作,可以在上面列出的任意組件中使用onLongPress屬性來實現(xiàn)
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'
}
});
3 手機效果如下
作者:chen.yu
深信服三年半工作經驗,目前就職游戲廠商,希望能和大家交流和學習,
微信公眾號:編程入門到禿頭 或掃描下面二維碼
零基礎入門進階人工智能(鏈接)