React封装弹出框组件

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

React封装弹出框组件

TA_WORLD   2022-09-29 我要评论

效果图

文件目录

alertList.tsx 用于容纳弹出框的容器

import React from "react";

export const HAlertList = () => {
    return (
        <div
            id="alert-list"
            style={{
                position:'fixed',
                top: '6%',
                left: '50%',
                transform: `translate(-50%)`
            }}
        ></div>
    )
}

将该组件置于项目根目录下的index.tsx

export const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  // <React.StrictMode>
  <>
    <Provider store={store}>
      <BrowserRouter>
        <App />
        <HAlertList/>
      </BrowserRouter>
    </Provider>
  </>
  // </React.StrictMode>
);

index.tsx 用于创建单个alert

规定传入的参数及类型

export interface HAlertProps {
    status:'success' | 'error',
    text:string
}

传入一个状态success或者error,用于区别样式

export const HAlert = (props:HAlertProps) => {
    return (
        <AlertContainer status={props.status}>
            {props.text}
        </AlertContainer>
    )
}


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 <HAlert {...value} key={index} />
                })}
            </>
        )
        setTimeout(() => {
            AlertList.list.shift()
            container.render(
                <>
                    {AlertList.list.map((value: HAlertProps, index: number) => {
                        return <HAlert {...value} key={index} />
                    })}
                </>
            )
        }, 2000)

    }
}

使用类编写对用的函数,是因为类是存储数据比较好的办法,AlertList .list存储着弹出框容器中所有弹出框的信息,AlertList.el为弹出框容器的节点
showAlert的逻辑:

1.查看AlertList.el是否有值,如果没有则创建创建节点

2.将该HAlert组件的信息存入AlertList .list

3.渲染弹出框列表

4.开启定时器(此处写的不是特别好),每隔2s取消一个HAlert

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们