一、簡介
按鈕組件在開發中最常見不過了,有文字,有事件,使用簡單,直接看API。注意此按鈕組件無法顯示圖片,如果需要顯示圖片,可以使用TouchableOpacity等可觸摸組件配合Image組件自定義按鈕。
二、API
常用的屬性和函數如下:
/** * Text to display inside the button * 按鈕文案 */ title: React.PropTypes.string.isRequired, /** * Text to display for blindness accessibility features * 輔助文案 */ accessibilityLabel: React.PropTypes.string, /** * Color of the text (iOS), or background color of the button (Android) * 按鈕文案顏色(iOS),安卓中則是背景顏色 */ color: ColorPropType, /** * If true, disable all interactions for this component. * 是否能交互 */ disabled: React.PropTypes.bool, /** * Handler to be called when the user taps the button * 點擊事件 */ onPress: React.PropTypes.func.isRequired, /** * Used to locate this view in end-to-end tests. * 按鈕標識,類似於iOS中的tag,便於在view子視圖數組中遍歷該按鈕 */ testID: React.PropTypes.string,
三、使用
將其作為View的子組件,設置大小背景色,示例如下:
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, View, Button } from 'react-native'; export default class ReactNativeDemo extends Component { render() { return ( <View style={[styles.flex,styles.bgColor,styles.center]}> <View style={[styles.center,{width:100, height:100, backgroundColor: 'green'}]}> <Button title={'點擊'} accessibilityLabel="accessibility title" color={'red'} disabled={false} testID={'buttonTag'} onPress={() => {console.log('-------')}} /> </View> </View> ); } } const styles = StyleSheet.create({ flex: { flex: 1 }, bgColor: { backgroundColor: '#1FB9FF' }, center: { alignItems: 'center', justifyContent: 'center' } }); AppRegistry.registerComponent('ReactNativeDemo', () => ReactNativeDemo);
2019-12-31 16:05:53.921 [info][tid:com.facebook.react.JavaScript] -------

