您现在的位置是:网站首页> 编程资料编程资料

React封装弹出框组件的方法_React_

2023-05-24 233人已围观

简介 React封装弹出框组件的方法_React_

本文实例为大家分享了React封装弹出框组件的方法,供大家参考,具体内容如下

效果图

文件目录

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

import React from "react"; export const HAlertList = () => {     return (         
    ) }

将该组件置于项目根目录下的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的逻辑:

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

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

3.渲染弹出框列表

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

-六神源码网