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

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

技术教程推荐

技术领导力实战笔记 -〔TGO鲲鹏会〕

SQL必知必会 -〔陈旸〕

TypeScript开发实战 -〔梁宵〕

爱上跑步 -〔钱亮〕

人人都用得上的写作课 -〔涵柏〕

高楼的性能工程实战课 -〔高楼〕

手把手带你写一个Web框架 -〔叶剑峰〕

说透元宇宙 -〔方军〕

AI大模型之美 -〔徐文浩〕

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