Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

React Native Android 自定義元件流程

編輯:關於 Android 開發

React Native Android 自定義元件流程

在 React Native 中,自定義元件可將重複使用的 UI 結構封裝起來。本文以一個包含圖示、文字與可設定背景色的元件為例,說明完整流程。

建立 item.js

在專案目錄下建立 item.js,使用 React.createClass 建立元件,並透過 module.exports 導出。

var Item = React.createClass({
    render: function() {
        var outStyle = {
            width: parseInt(this.props.width),
            height: parseInt(this.props.height),
            backgroundColor: this.props.color
        };
        var img = this.props.img;
        var text = this.props.text;
        return (
            <View style={[styles.item, outStyle]}>
                <Image style={styles.image} source={{uri: img}} />
                <Text style={styles.text}>{text}</Text>
            </View>
        );
    }
});
module.exports = Item;

樣式合併

元件內可先定義基礎樣式,再透過樣式陣列與外部傳入的 style 合併,讓外部可覆寫寬高、背景色等屬性。

var styles = StyleSheet.create({
    item: {
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 10
    },
    image: {
        width: 48,
        height: 48
    },
    text: {
        color: '#ffffff'
    }
});

使用方式

在其他檔案中引入元件,並傳入 color、width、height、text 與 img 即可。

var Item = require('./item');

這種做法能讓 UI 元件更清楚、可測試,也方便後續擴充更多自定義屬性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved