Material ui 全局消息组件

文章目录


前言

学习material ui系列,解决全局组件问题


一、为什么需要全局组件

异常全局提示,操作成功提醒等,需要一个函数直接渲染,而不是通过当前组件的状态来管理组件。

二、自定义全局组件

1.定义消息提示组件

从material ui的文档来看,官方推荐使用Snackbar组件,代码如下(GlobalSnackbars.js)(示例):

import React, {Fragment, useEffect, useState} from 'react';
import {Snackbar} from '@material-ui/core';
import {Alert as MuiAlert, AlertTitle} from '@material-ui/lab';
import message from "../util/message";

const GlobalSnackbars = () => {
    const [isOpen, setOpen] = useState(false);
    const [severity, setSeverity] = useState("info");
    const [content, setContent] = useState("");
    
    const handleClose = (_, reason) => {
        if(reason === 'clickaway'){
            return;
        }
        this.setState({
            isOpen: false
        })
    };

    return (
        <Fragment>
            <Snackbar open={isOpen} autoHideDuration={2000} onClose={handleClose}>
                <MuiAlert elevation={6} variant={"filled"} onClose={handleClose} severity={severity}>
                    <AlertTitle>{severity.toLocaleUpperCase()}</AlertTitle>
                    {content}
                </MuiAlert>
            </Snackbar>
        </Fragment>
    )
}

export default GlobalSnackbars;

2.设计函数

这里采用静态方法,模仿antd的消息提示接口。代码如下(message.js)(示例):

export default class message {
    static info = (msg) => {}
    static warn = (msg) => {}
    static success = (msg) => {}
    static error = (msg) => {}
}

3.通过函数改变全局组件状态

在GlobalSnackbars组件中添加useEffect副作用,通过步骤2的静态函数,来改变Snackbar状态。添加代码如下(GlobalSnackbars.js)(示例):

	useEffect(() => {
        message.info = (msg) => {
          setOpen(true);
          setSeverity("info");
          setContent(msg);
        };
        message.warn = (msg) => {
            setOpen(true);
            setSeverity("warn");
            setContent(msg);
        };
        message.success = (msg) => {
            setOpen(true);
            setSeverity("success");
            setContent(msg);
        };
        message.error = (msg) => {
            setOpen(true);
            setSeverity("error");
            setContent(msg);
        };
    }, [])

总结

通过静态函数来启动一些组件,也是自定义组件的一种方式

上一篇:一组强大的CSS3 Material 按钮


下一篇:jquery animate stop函数解析