React Native添加自定义全局组件

在开发rnApp的时候想自己封装一个自定义的Toast组件,又不想在每个组件文件内单独引用,于是自己琢磨了一个方法将组件添加到全局。

这里举例封装一个自定义的Toast组件,这个文件可以放在自己的公共组件文件夹下

ToastTip.js

/*
 * @Date: 2020-02-26 17:40:34
 * @Description: 自己封装Toast提示
 * @Author: YooHoeh
 * @LastEditors: YooHoeh
 * @LastEditTime: 2020-02-28 18:09:17
 */

import React, { Component } from "react";
import { StyleSheet, Text, View, Dimensions, Modal } from "react-native";
const windows = Dimensions.get("window");
export default class ToastTip extends Component {
    constructor() {
        super();
        this.state = {
            modalVisible: false,
            content: undefined
        };
    }

    show(content) {
        setTimeout(() => {
            this.setModalVisible(false);
        }, 1800);
        this.setState({
            modalVisible: true,
            content
        });
    }

    setModalVisible(visible) {
        this.setState({ modalVisible: visible });
    }

    render() {
        if (!this.state.modalVisible) return <View />;
        const { content } = this.state;
        return (
            <Modal
                animationType="slide"
                transparent={true}
                visible={this.state.modalVisible}
                onRequestClose={() => {
                    alert("Modal has been closed.");
                }}
            >
                <View style={styles.container}>
                    <View style={styles.content}>
                        <Text style={styles.contentText}>{content}</Text>
                    </View>
                </View>
            </Modal>
        );
    }
}
module.exports = ToastTip;

const styles = StyleSheet.create({
    container: {
        position: "absolute",
        bottom: 50,
        width: windows.width,
        justifyContent: "center",
        alignItems: "center"
    },
    content: {
        borderRadius: 4,
        paddingVertical: 4,
        paddingHorizontal: 8,
        backgroundColor: "#000000cc"
    },
    contentText: {
        color: "#fff",
        lineHeight: 17
    }
});

然后在项目根目录下,找到App.js文件

导入ToastTip组件,然后在render生命周期里将组件渲染,这里需要注意:必须将组件作为在顶层容器的第一个子组件,否则可能出现公共组件调用时未渲染。

App.js

import ToastTip from "./components/ToastTip";
……
class App extends Component {
……
        render(){
                return (<View>
                         //这里用global而不用this。
                         //$toastTip可以自己随意更改,我这里添加$只是为了使用时区别一般变量。
                        <ToastTip ref={toastTip => global.$toastTip = toastTip}/>  
                        ……
                </View>)
        }
}

使用方法如下

在任意想要调用的文件内,无需另外引入。

xxx.js

class xxx {
        xx(){
                $toastTip.show('Bingo!')
        }
}