materialUi 没有合适的 消息通知组件, 这里使用 Snackbar 和 Alert 开发一个
### 效果
![](https://img.kancloud.cn/e6/d9/e6d9e824ee83ab7d86699688886a56b3_700x327.png)
### 完整代码
ToastItem.tsx
```
import React from "react";
import { Snackbar, Alert } from '@mui/material';
export default (props: any) => {
const { content, duration=3000, type } = props;
// 开关控制:默认true,调用时会直接打开
const [open, setOpen] = React.useState(true);
// 关闭消息提示
const handleClose = () => {
setOpen(false);
};
return <Snackbar
open={open}
autoHideDuration={duration}
anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
onClose={handleClose}>
<Alert onClose={handleClose} severity={type}>{content}</Alert>
</Snackbar>
}
```
index.tsx
```
import ToastItem from "./ToastItem";
import ReactDOM from "react-dom";
const Toast = {
dom: null,
success(content: any, duration?: any) {
// 创建一个dom
let dom = document.createElement('div');
// 定义组件,
const JSXdom = (<ToastItem content={content} duration={duration} type='success'/>);
// 渲染DOM
ReactDOM.render(JSXdom, dom)
// 置入到body节点下
document.body.appendChild(dom);
},
error(content: any, duration?: any) {
let dom = document.createElement('div');
const JSXdom = (<ToastItem content={content} duration={duration} type='error'/>);
ReactDOM.render(JSXdom, dom)
document.body.appendChild(dom);
},
warning(content: any, duration?: any) {
let dom = document.createElement('div');
const JSXdom = (<ToastItem content={content} duration={duration} type='warning'/>);
ReactDOM.render(JSXdom, dom)
document.body.appendChild(dom);
},
info(content: any, duration?: any) {
let dom = document.createElement('div');
const JSXdom = (<ToastItem content={content} duration={duration} type='info' />);
ReactDOM.render(JSXdom, dom)
document.body.appendChild(dom);
}
};
export default Toast;
```
### 使用
```
其他代码省略
import Toast from "../Toast";
function onCopy () {
Toast.success("复制成功");
}
```
[参考的js 版本](https://blog.csdn.net/u012885136/article/details/122490041)