日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React封裝彈出框組件的方法_React

作者:TA_WORLD ? 更新時間: 2022-10-19 編程語言

本文實例為大家分享了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

原文鏈接:https://blog.csdn.net/qq_56303170/article/details/126004127

欄目分類
最近更新