React Native组件之Button

不管在Android还是ios开发中,系统都有Button组件,而在早期的React Native中,系统是不提供Button组件的,一般会使用一个叫做react-native-button的库。

Button组件

Button组件其实就是 Touchable(TouchableNativeFeedback、TouchableOpacity)和Text封装。核心源码如下:

render() {
    const {
      accessibilityLabel,color,onPress,title,disabled,} = this.props;
    const buttonStyles = [styles.button];
    const textStyles = [styles.text];
    const Touchable = Platform.OS === 'android' ? TouchableNativeFeedback : TouchableOpacity;
    if (color && Platform.OS === 'ios') {
      textStyles.push({color: color});
    } else if (color) {
      buttonStyles.push({backgroundColor: color});
    }
    if (disabled) {
      buttonStyles.push(styles.buttondisabled);
      textStyles.push(styles.textdisabled);
    }
    invariant(
      typeof title === 'string','The title prop of a Button must be a string',);
    const formattedTitle = Platform.OS === 'android' ? title.toupperCase() : title;
    return (
      <Touchable
        accessibilityComponentType="button"
        accessibilityLabel={accessibilityLabel}
        accessibilityTraits={['button']}
        disabled={disabled}
        onPress={onPress}>
        <View style={buttonStyles}>
          <Text style={textStyles}>{formattedTitle}</Text>
        </View>
      </Touchable>
    );
      }

Button常用属性

titleButton显示的文本
accessibilityLabel是用于盲文的,读屏器软件可能会读取这一内容
colorios表示字体的颜色,android表示背景的颜色
disabled是否可用,如果为true,禁用此组件的所有交互
onPress点击触发函数

实例

import React,{Component} from 'react';
    import {
        StyleSheet,View,Button,ToastAndroid,} from 'react-native';

    export default class ButtonDemo extends Component {

    render() {
        return (
            <View style={{flex:1}}>
                <Button title='认Button' accessibilityLabel='accessibilityLabel'/>
                <Button title='color设置为红色' color='red' />
                <Button title='禁用' disabled={true} onPress={()=>{
                    ToastAndroid.show('点我了');
                }}/>
                <Button title='禁用' onPress={()=>{
                    ToastAndroid.show('点我了',ToastAndroid.SHORT);
                }}/>
            </View>
        );
    }
    }

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...