本文实例为大家分享了React封装弹出框组件的方法,供大家参考,具体内容如下
效果图
文件目录
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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did121889