React Native学习(8)处理触摸事件
创建一个简单的按钮
触摸时间一般为按钮、滑动、缩放等等。
先来创建一个最简单的按钮:
/**
* 慢慢学习
* https://blog.csdn.net/quanhaoH
*/
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View, TextInput, Image , Button, Alert} from 'react-native';
export default class MyApp extends Component {
render() {
return (
<View>
<Button
onPress={() => {
Alert.alert("你点击了按钮!");
}}
title="我是一个按钮"
/>
</View>
);
}
}
AppRegistry.registerComponent('MyApp', () => MyApp);
当你点击按钮的时候,会调用onPress函数,这个函数的作用就是弹出一个Alert窗口。
Touchable 系列组件
如下:
/**
* 慢慢学习
* https://blog.csdn.net/quanhaoH
*/
import React, { Component } from 'react';
import { Alert, AppRegistry, Platform, StyleSheet, Text, TouchableHighlight, TouchableOpacity, TouchableNativeFeedback, TouchableWithoutFeedback, View } from 'react-native';
export default class MyApp extends Component {
_onPressButton() {
Alert.alert('You tapped the button!')
}
_onLongPressButton() {
Alert.alert('You long-pressed the button!')
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight onPress={this._onPressButton} underlayColor="white">
<View style={styles.button}>
<Text style={styles.buttonText}>TouchableHighlight</Text>
</View>
</TouchableHighlight>
<TouchableOpacity onPress={this._onPressButton}>
<View style={styles.button}>
<Text style={styles.buttonText}>TouchableOpacity</Text>
</View>
</TouchableOpacity>
<TouchableNativeFeedback
onPress={this._onPressButton}
background={Platform.OS === 'android' ? TouchableNativeFeedback.SelectableBackground() : ''}>
<View style={styles.button}>
<Text style={styles.buttonText}>TouchableNativeFeedback</Text>
</View>
</TouchableNativeFeedback>
<TouchableWithoutFeedback
onPress={this._onPressButton}
>
<View style={styles.button}>
<Text style={styles.buttonText}>TouchableWithoutFeedback</Text>
</View>
</TouchableWithoutFeedback>
<TouchableHighlight onPress={this._onPressButton} onLongPress={this._onLongPressButton} underlayColor="white">
<View style={styles.button}>
<Text style={styles.buttonText}>Touchable with Long Press</Text>
</View>
</TouchableHighlight>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
paddingTop: 60,
alignItems: 'center'
},
button: {
marginBottom: 30,
width: 260,
alignItems: 'center',
backgroundColor: '#2196F3'
},
buttonText: {
padding: 20,
color: 'white'
}
})
AppRegistry.registerComponent('MyApp', () => MyApp);