React Native 封装页面基类BaseComponent

我在react native 开发时。基本每个页面都要处理下面的问题。
1.为每个页面包裹一层SafeArea用于适配iPhoneX以及后续机型
2.处理每一个页面的安卓返回键
3.状态栏的颜色等配置
移动端原生开发时。我们会给每一个一面写一个基类。封装一些配置和功能。后续的页面都继承这个基类,起到便捷作用。所以我封装了一个这样的基类,用于快捷处理上面遇到的问题。

import React, { Component } from "react";
import { StatusBar, StyleSheet, Platform } from "react-native";
import { SafeAreaView } from "react-navigation";
import { BackHandler } from "react-native";

export default class Base extends Component {
    constructor(props) {
        super(props);
        if (props.navigation) {
            //如果是在nav中的组件。添加安卓返回键监听
            this._didFocusSubscription = props.navigation.addListener(
                "didFocus",
                payload =>
                    BackHandler.addEventListener(
                        "hardwareBackPress",
                        this._onBackButtonPressAndroid
                    )
            );
        }
    }
    /**
     * 可以在继承类中重写的方法
     */
    //状态栏配置文件
    _statusBarConfig = {};
    //处理安卓返回键,默认直接可以返回,子继承类中重写此方法可以自定义处理安卓返回键
    _onBackButtonPressAndroid = () => {
        //当return true时,会阻止默认的返回事件
        return false;
    };

    /**
     * LifeCircle
     * 在被继承的Component中重写这两个方法作为新的生命周期使用
     * !!!!!一定要使用箭头函数的形式
     * 不要重写旧的componentDidMount和DidUnmount
     */

    BaseComponentWillMount = () => {};
    BaseRender = () => {};
    BaseComponentDidMount = () => {};
    BaseComponentWillUnmount = () => {};
    /**
     * 原有lifeCircle
     */

    componentDidMount = () => {
        if (this.props.navigation) {
            //添加状态栏以及安卓返回键监听
            Platform.OS === "android" && this.setAndroidBackListener();
            this.setStatusBarListener();
        }
        this.BaseComponentDidMount();
    };
    UNSAFE_componentWillMount = () => {
        this.BaseComponentWillMount();
    };
    componentWillUnmount = () => {
        this._statusBarListener && this._statusBarListener.remove();
        this._didFocusSubscription && this._didFocusSubscription.remove();
        this._willBlurSubscription && this._willBlurSubscription.remove();
        this.BaseComponentWillUnmount();
    };

    //添加页面切换时状态栏监听
    setStatusBarListener = () => {
        const barConfig = {
            contentType: "dark-content", //状态栏文字颜色 enum('default', 'light-content', 'dark-content')
            androidTranslucent: true, //状态栏是否沉浸式。需要配合backgroundColor为透明色来一起配置
            androidBarBackgroundColor: null, //状态栏背景颜色
            hidden: false, //是否隐藏状态栏
            ...this._statusBarConfig
        };
        this._statusBarListener = this.props.navigation.addListener(
            "didFocus",
            () => {
                StatusBar.setBarStyle(barConfig.contentType);
                StatusBar.setHidden(barConfig.hidden);
                //安卓沉浸式
                if (Platform.OS === "android") {
                    StatusBar.setTranslucent(barConfig.androidTranslucent);
                    if (barConfig.androidTranslucent) {
                        //安卓沉浸式
                        StatusBar.setBackgroundColor("transparent");
                    } else {
                        barConfig.androidBarBackgroundColor &&
                            StatusBar.setBackgroundColor(barConfig.androidBarBackgroundColor);
                    }
                }
            }
        );
    };
    setAndroidBackListener = () => {
        this._willBlurSubscription = this.props.navigation.addListener(
            "willBlur",
            payload =>
                BackHandler.removeEventListener(
                    "hardwareBackPress",
                    this._onBackButtonPressAndroid
                )
        );
    };

    render = () => {
        return (
            <SafeAreaView
                style={[baseStyles.safeArea, this.safeAreaStyles]}
                forceInset={this.forceInset}
            >
                {this.BaseRender()}
            </SafeAreaView>
        );
    };
}

const baseStyles = StyleSheet.create({
    safeArea: {
        backgroundColor: '#ffffff',
        flex: 1
    }
});

然后在新建页面时继承这个类,新建的页面如下

import React from "react";
import { View } from "src/Utility/PathExport";
import BaseComponent from "src/UI/Pages/BaseComponent";
import MainView from "./view";


/**
 * 新建页面中用BaseComponentDidMount等代替原有的ComponentDidMount等生命周期,方法一定要写成箭头函数的形式,否则不识别
 */

//新建的类继承于BaseComponent
export default  class index extends BaseComponent {
    static navigationOptions = {title:'Example'};
    //状态栏配置。BaseComponent会读取,涉及到样式配置全都写在view.js里
    statusBarConfig = {
        contentType: "light-content",
        androidTranslucent: false,
        androidBarBackgroundColor: 'red', //状态栏背景颜色
        hidden: false, //是否隐藏状态栏
    };;

    _onBackButtonPressAndroid = () => {
        //当return true时,会阻止默认的返回事件,false时则会响应
        alert("Back On Press");
        return true;
    };

    //新的生命周期写法
    BaseComponentDidMount = () => {
    };
    BaseComponentWillUnmount = () => {};


    BaseRender = () => {
        return (
            <View style={{ flex: 1 }}>
              <MainView />
            </View>
        );
    };
}

这样。我们就把上面的结构问题封装到基类中了。如果用别的常用配置也可以自己再添加在基类里。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,160评论 1 32
  • 在一个方法内部定义的变量都存储在栈中,当这个函数运行结束后,其对应的栈就会被回收,此时,在其方法体中定义的变量将不...
    Y了个J阅读 4,450评论 1 14
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,267评论 4 61
  • 校区:科学创想乐高机器人茂业校区 ✔班级: 【周六下午12:10--1:10。学员:刘穆泽,张圣群,王梓图,吴皓森...
    A越单纯越幸福阅读 727评论 0 0
  • 这几天练字群里人头攒动,学员抛出的问题层出不穷,像大海里那些泡沫一样,层层叠叠,大大小小,一堆堆,一簇簇。蔚为壮观...
    蝶化文澜阅读 463评论 1 2