效果图
文件目录
alertList.tsx 用于容纳弹出框的容器
import React from "react";
export const HAlertList = () => {
return (
{
position:'fixed',
top: '6%',
left: '50%',
transform: `translate(-50%)`
}}
>
)
}
将该组件置于项目根目录下的index.tsx
export const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
//
<>
>
//
);
index.tsx 用于创建单个alert
规定传入的参数及类型
export interface HAlertProps {
status:'success' | 'error',
text:string
}
传入一个状态success
或者error
,用于区别样式
export const HAlert = (props:HAlertProps) => {
return (
{props.text}
)
}
const AlertContainer = styled.div<{
status:string
}>`
width: 65vw;
height: 30px;
background-color: ${props => props.status === 'success' ? '#a8dda8' : '#ff4b4b'};
text-align: center;
margin-bottom: 10px;
`
此处使用emotion
(css-in-js)的技术,即使用js编写css样式
当HTML文档中识别到AlertContainer
标签时,会转变为具有对应样式的div
标签
use.tsx 函数式调用alert组件
import React, { useState } from 'react'
import ReactDOM from 'react-dom/client'
import { HAlertProps, HAlert } from './index'
export class AlertList {
static list: HAlertProps[] = []
static el: ReactDOM.Root | null = null
static showAlert = (props: HAlertProps) => {
let container: ReactDOM.Root
if (AlertList.el) {
container = AlertList.el
} else {
AlertList.el = container = ReactDOM.createRoot(
document.getElementById('alert-list') as HTMLElement
)
}
AlertList.list.push(props)
container.render(
<>
{AlertList.list.map((value: HAlertProps, index: number) => {
return
})}
>
)
setTimeout(() => {
AlertList.list.shift()
container.render(
<>
{AlertList.list.map((value: HAlertProps, index: number) => {
return
})}
>
)
}, 2000)
}
}
使用类编写对用的函数,是因为类是存储数据比较好的办法,AlertList .list
存储着弹出框容器中所有弹出框的信息,AlertList.el
为弹出框容器的节点
showAlert
的逻辑:
AlertList.el
是否有值,如果没有则创建创建节点HAlert
组件的信息存入AlertList .list
中HAlert