当前位置:首页 > React

react如何做toast提示

2026-01-25 04:36:46React

使用 react-hot-toast 库

安装 react-hot-toast 库:

npm install react-hot-toast

在应用的根组件中引入 Toaster 组件:

import { Toaster } from 'react-hot-toast';

function App() {
  return (
    <div>
      <Toaster />
      {/* 其他组件 */}
    </div>
  );
}

在需要显示 toast 的地方调用 toast 方法:

import toast from 'react-hot-toast';

// 基本用法
toast('This is a toast message');

// 成功提示
toast.success('Successfully saved!');

// 错误提示
toast.error('Something went wrong');

// 加载中提示
const loadingToast = toast.loading('Processing...');
// 完成后更新
setTimeout(() => {
  toast.dismiss(loadingToast);
  toast.success('Done!');
}, 2000);

使用 Chakra UI 的 Toast 组件

安装 Chakra UI:

react如何做toast提示

npm install @chakra-ui/react @emotion/react @emotion/styled framer-motion

设置 ChakraProvider:

import { ChakraProvider } from '@chakra-ui/react';

function App() {
  return (
    <ChakraProvider>
      {/* 其他组件 */}
    </ChakraProvider>
  );
}

使用 useToast hook:

react如何做toast提示

import { useToast } from '@chakra-ui/react';

function Component() {
  const toast = useToast();

  const showToast = () => {
    toast({
      title: 'Toast Title',
      description: 'This is a toast description',
      status: 'success',
      duration: 3000,
      isClosable: true,
      position: 'top-right'
    });
  };

  return <button onClick={showToast}>Show Toast</button>;
}

自定义 Toast 组件

创建一个可复用的 Toast 组件:

import React, { useState, useEffect } from 'react';
import './Toast.css';

const Toast = ({ message, type, duration = 3000, onClose }) => {
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    const timer = setTimeout(() => {
      setVisible(false);
      onClose();
    }, duration);

    return () => clearTimeout(timer);
  }, [duration, onClose]);

  return visible ? (
    <div className={`toast toast-${type}`}>
      {message}
    </div>
  ) : null;
};

export default Toast;

使用上下文管理全局 Toast:

import React, { createContext, useContext, useState } from 'react';
import Toast from './Toast';

const ToastContext = createContext();

export const ToastProvider = ({ children }) => {
  const [toasts, setToasts] = useState([]);

  const addToast = (message, type) => {
    const id = Date.now();
    setToasts([...toasts, { id, message, type }]);
    setTimeout(() => {
      removeToast(id);
    }, 3000);
  };

  const removeToast = (id) => {
    setToasts(toasts.filter(toast => toast.id !== id));
  };

  return (
    <ToastContext.Provider value={{ addToast }}>
      {children}
      <div className="toast-container">
        {toasts.map(toast => (
          <Toast 
            key={toast.id}
            message={toast.message}
            type={toast.type}
            onClose={() => removeToast(toast.id)}
          />
        ))}
      </div>
    </ToastContext.Provider>
  );
};

export const useToast = () => {
  return useContext(ToastContext);
};

CSS 样式示例

为自定义 Toast 添加基础样式:

.toast-container {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
}

.toast {
  padding: 12px 24px;
  margin-bottom: 10px;
  border-radius: 4px;
  color: white;
  animation: slideIn 0.3s ease-out;
}

.toast-success {
  background-color: #48BB78;
}

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

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

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

标签: 如何做提示
分享给朋友:

相关文章

vue实现下载提示

vue实现下载提示

Vue 实现下载提示功能 在 Vue 中实现下载提示功能,可以通过以下几种方式实现: 方法一:使用 window.confirm 在触发下载操作前,通过 window.confirm 弹出确认对话…

vue实现编辑提示功能

vue实现编辑提示功能

实现编辑提示功能的步骤 使用v-model绑定数据 在Vue中,可以通过v-model指令实现双向数据绑定。在编辑模式下,将输入框与数据绑定,非编辑模式下显示文本内容。 <template&g…

vue实现语法高亮提示

vue实现语法高亮提示

使用 Prism.js 实现语法高亮 安装 Prism.js 库 通过 npm 或 yarn 安装 Prism.js 核心库及需要的语言插件: npm install prismjs 引入 Pris…

react如何做title

react如何做title

如何在React中动态设置页面标题 使用React Helmet库可以轻松管理文档头部标签 安装依赖包npm install react-helmet或yarn add react-helmet 在组…

react项目如何做反向代理

react项目如何做反向代理

反向代理的作用 反向代理可以帮助开发阶段解决跨域问题,或在生产环境隐藏真实服务器信息。React项目通常结合开发服务器或Nginx实现反向代理。 开发环境配置(Create React App) 在…

react 上传组件图片如何做回显

react 上传组件图片如何做回显

实现图片上传与回显 在React中实现图片上传并回显通常需要结合文件输入控件和状态管理。以下是具体实现方法: 使用FileReader API读取图片 创建一个状态变量存储图片数据,通过FileRe…