1. 程式人生 > >React Native自定義標題欄元件

React Native自定義標題欄元件

大家好,今天講一下如何實現自定義標題欄元件,我們都知道RN有一個優點就是可以元件化,在需要使用該元件的地方直接引用並傳遞一些引數就可以了,這種方式確實提交了開發效率。
標題欄是大多數應用介面必不可少的一部分,將標題欄剝離出來做成一個元件很有必要。今天先講一個不帶返回按鈕的標題欄。廢話少說,直接上程式碼:


/**
 * 封裝公共的標題頭,沒有返回按鈕
 */
'use strict';
import React, { Component } from 'react';
import {
    Text,
    View,
}
from 'react-native';
import StyleSheet from 'StyleSheet';


export default class HeaderNoBack extends Component {
    render() {
        return (
                <View style={styles.container}>
                    <View style={styles.textview}>
                        <Text style={styles.textstyle}>{this.props.text || "標題頭"}</Text>
                    </View>
                </View>
        );
    }
}


const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 45,
        alignSelf: 'stretch',
        backgroundColor: '#4a9df8',
    },
    textview: {
        flex: 1,
        alignSelf: 'center',
    },
    textstyle: {
        fontSize: 18,
        color: '#fff',
        textAlign: 'center',
    },
});



程式碼比較簡單,這裡就做過多的分析了,但是著重說一點,this.props.text這裡是顯示傳入進來的要顯示的文字,如果沒有傳入text屬性,則預設顯示"標題頭"。
使用方法示例:
import HeaderNoBack from '../../../component/Header/HeaderNoBack';
<HeaderNoBack text='我是標題'/>

以上程式碼主要用到了View和Text元件,樣式使用了flex佈局,有不瞭解felx佈局的可以看下阮一峰的一篇文章:

當然,網上資料很多,也可以自己搜尋,上面只是程式碼示例,在實際專案中要根據自己的情況進行修改。
好了,今天先講到這裡,後面部分會講解帶返回按鈕的標題欄的實現。