大多数用户通过触摸与移动设备进行互动。可以使用多种手势组合,例如点击按钮,缩放地图,滚动列表等。按钮是单击时可以使用的组件之一。
React Native Button是一个基本组件,可以通过单击它来工作。它导入React-native的Button类。
Prop | Type | Required | Description |
---|---|---|---|
onPress | function | yes | 用户单击按钮时调用处理程序。 |
title | string | yes | 在按钮内显示文本。 |
accessibilityLabel | string | no | 显示用于辅助函数的文本。 |
color | Color | no | 设置Android按钮的背景颜色或设置iOS文本的颜色。 |
disabled | bool | no | 如果为true,它将禁用此组件的所有交互。 |
textID | string | no | 用于在端到端测试中定位此视图。 |
hasTVPreferredFocus | bool | no | 它更喜欢仅针对Apple TV的电视焦点工作。 |
在此示例中,我们将处理按钮组件。 React Native Button组件导入react-native库的Button类。它具有上面提到的几个道具,例如标题,onPress,accessibilityLabel等。
在上一篇文章“使用Flex定位元素”中,我们学习了如何在View中定位元素。
在下面代码中,title属性设置按钮的标题,onPress属性调用提及函数并执行一个事件。 color prop设置按钮的颜色,而disable = {true}则使按钮禁用。
import React, { Component } from 'react'; import { Alert, AppRegistry, Button, StyleSheet, View } from 'react-native'; export default class ButtonBasics extends Component { onPressButton() { Alert.alert('You clicked the button!') } render() { return ( <View style={styles.container}> <View style={styles.buttonContainer}> <Button onPress={this.onPressButton} title="Press Me" /> </View> <View style={styles.buttonContainer}> <Button onPress={this.onPressButton} title="Press Me" color="#009933" /> </View> <View style={styles.multiButtonContainer}> <Button onPress={this.onPressButton} title="A disabled button" disabled={true} /> <Button onPress={this.onPressButton} title="OK!" color="#009933" /> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', }, buttonContainer: { margin: 20 }, multiButtonContainer: { margin: 20, flexDirection: 'row', justifyContent: 'space-between' } })
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)