前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >React Native组件之Button

React Native组件之Button

作者头像
xiangzhihong
发布2018-02-06 16:16:48
1.3K0
发布2018-02-06 16:16:48
举报
文章被收录于专栏:向治洪向治洪

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

Button组件

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

代码语言:javascript
复制
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点击触发函数

实例

这里写图片描述
这里写图片描述
代码语言:javascript
复制
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>
        );
    }
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-05-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Button组件
    • Button常用属性
      • 实例
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档