React Native组件之Button

前端之家收集整理的这篇文章主要介绍了React Native组件之Button前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

Button组件

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

  1. render() {
  2. const {
  3. accessibilityLabel,color,onPress,title,disabled,} = this.props;
  4. const buttonStyles = [styles.button];
  5. const textStyles = [styles.text];
  6. const Touchable = Platform.OS === 'android' ? TouchableNativeFeedback : TouchableOpacity;
  7. if (color && Platform.OS === 'ios') {
  8. textStyles.push({color: color});
  9. } else if (color) {
  10. buttonStyles.push({backgroundColor: color});
  11. }
  12. if (disabled) {
  13. buttonStyles.push(styles.buttonDisabled);
  14. textStyles.push(styles.textDisabled);
  15. }
  16. invariant(
  17. typeof title === 'string','The title prop of a Button must be a string',);
  18. const formattedTitle = Platform.OS === 'android' ? title.toUpperCase() : title;
  19. return (
  20. <Touchable
  21. accessibilityComponentType="button"
  22. accessibilityLabel={accessibilityLabel}
  23. accessibilityTraits={['button']}
  24. disabled={disabled}
  25. onPress={onPress}>
  26. <View style={buttonStyles}>
  27. <Text style={textStyles}>{formattedTitle}</Text>
  28. </View>
  29. </Touchable>
  30. );
  31. }

Button常用属性

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

实例

  1. import React,{Component} from 'react';
  2. import {
  3. StyleSheet,View,Button,ToastAndroid,} from 'react-native';
  4.  
  5. export default class ButtonDemo extends Component {
  6.  
  7. render() {
  8. return (
  9. <View style={{flex:1}}>
  10. <Button title='默认Button' accessibilityLabel='accessibilityLabel'/>
  11. <Button title='color设置为红色' color='red' />
  12. <Button title='禁用' disabled={true} onPress={()=>{
  13. ToastAndroid.show('点我了');
  14. }}/>
  15. <Button title='禁用' onPress={()=>{
  16. ToastAndroid.show('点我了',ToastAndroid.SHORT);
  17. }}/>
  18. </View>
  19. );
  20. }
  21. }

猜你在找的React相关文章