首页 > web前端 > js教程 > 正文

在 React 中使用特定类型和上下文 API 设置 Toast 自定义通知

WBOY
发布: 2024-07-23 18:38:23
原创
366 人浏览过

Setting Up Toast Custom Notifications in React with Specific Types and Context API

上下文设置

src/context/ToastContext.js

import { createContext, useCallback, useContext, useEffect, useState } from "react";

const CreateAlertBox = createContext();

export const useCreateAlert = () => useContext(CreateAlertBox);

const AlertType = ['error', 'success', 'info', 'warning'];

export const CreateAlertBoxProvider = ({ children }) => {
    const [alert, setAlert] = useState([]);

    const createAlert = useCallback((message, type = 'warning') => {
        if (!AlertType.includes(type)) return;

        setAlert((prevAlert) => [
            ...prevAlert,
            { id: Date.now(), message, type }
        ])
    }, [])

    const removeAlert = useCallback((id) => {
        setAlert((prevAlert) => prevAlert.filter((alert) => alert.id !== id));
    }, [])
    return (
        <CreateAlertBox.Provider value={{ createAlert, removeAlert }}>
            {children}
            <div className="toast-container">
                {
                    alert.map((alert) => (
                        <div key={alert.id} className={`toast toast-${alert.type}`}>
                            {alert.message}
                            <button onClick={() => removeAlert(alert.id)}>X</button>
                        </div>
                    ))
                }
            </div>
        </CreateAlertBox.Provider>
    )
}
登录后复制

Toast 通知的 CSS

/* src/styles/toast.css */

.toast-container {
    position: fixed;
    top: 1rem;
    right: 1rem;
    z-index: 9999;
}

.toast {
    background-color: #333;
    color: #fff;
    padding: 1rem;
    margin-bottom: 1rem;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.toast-info {
    background-color: #007bff;
}

.toast-success {
    background-color: #28a745;
}

.toast-warning {
    background-color: #ffc107;
}

.toast-error {
    background-color: #dc3545;
}

.toast button {
    background: none;
    border: none;
    color: #fff;
    cursor: pointer;
    margin-left: 1rem;
}

登录后复制

提供 Toast 上下文

// src/main.js

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
import { RouterProvider } from 'react-router-dom'
import { router } from './router.jsx'
import { CreateAlertBoxProvider } from './context/toastcontext.jsx'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <CreateAlertBoxProvider>
        <RouterProvider router={router}>
          <App />
        </RouterProvider>
    </CreateAlertBoxProvider>
  </React.StrictMode>,
)

登录后复制

在组件中使用 Toast 上下文

import React, { useContext, useEffect } from 'react'
import { UserContext } from '../context/usercontext'
import { useCreateAlert } from '../context/toastcontext'

const Profile = () => {
    const { user } = useContext(UserContext)

    const { createAlert } = useCreateAlert();

    const showToast = () => {
        try {
            createAlert("Deal created successfully", 'success')

        } catch (error) {
            createAlert('This is an info toast!', 'error');
        }
    };


    return (
        <div className="App">
            <p>Hello Profile</p>
            <button onClick={showToast}>Show Toast</button>
        </div>
    )
}

export default Profile
登录后复制

以上是在 React 中使用特定类型和上下文 API 设置 Toast 自定义通知的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板