React Native - Button

React Native - Button 首页 / React Native入门教程 / React Native - Button

大多数用户通过触摸与移动设备进行互动。可以使用多种手势组合,例如点击按钮,缩放地图,滚动列表等。按钮是单击时可以使用的组件之一。

React Native Button是一个基本组件,可以通过单击它来工作。它导入React-native的Button类。

无涯教程网

按钮属性

PropTypeRequiredDescription
onPressfunctionyes用户单击按钮时调用处理程序。
titlestringyes在按钮内显示文本。
accessibilityLabelstringno显示用于辅助函数的文本。
colorColorno设置Android按钮的背景颜色或设置iOS文本的颜色。
disabledboolno如果为true,它将禁用此组件的所有交互。
textIDstringno用于在端到端测试中定位此视图。
hasTVPreferredFocusboolno它更喜欢仅针对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'
    }
})

输出:

React Native ButtonReact Native Button

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

左耳听风 -〔陈皓〕

推荐系统三十六式 -〔刑无刀〕

透视HTTP协议 -〔罗剑锋(Chrono)〕

Node.js开发实战 -〔杨浩〕

DevOps实战笔记 -〔石雪峰〕

Flink核心技术与实战 -〔张利兵〕

手把手教你玩音乐 -〔邓柯〕

如何成为学习高手 -〔高冷冷〕

现代C++20实战高手课 -〔卢誉声〕

好记忆不如烂笔头。留下您的足迹吧 :)