当前位置:首页 > 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 中实现消息提示功能可以通过多种方式完成,以下是几种常见的实现方法。 使用 Vue 插件(如 Element UI、Vant 等) Element UI 提供了…

vue实现搜索智能提示

vue实现搜索智能提示

实现搜索智能提示的方法 在Vue中实现搜索智能提示功能,可以通过以下步骤完成: 使用v-model绑定输入框 通过v-model绑定输入框的值,监听用户输入变化: <template>…

react icon 如何做

react icon 如何做

在 React 中使用图标的方法 安装图标库 React 项目可以通过流行的图标库(如 react-icons)快速集成图标。运行以下命令安装: npm install react-icons…

react如何做规划

react如何做规划

React 项目规划方法 明确项目目标和需求 在开始开发前,需要清晰地定义项目的目标和需求。列出核心功能、用户交互流程和预期的用户体验。撰写详细的需求文档或用户故事,确保团队成员对目标有统一理解。…

react如何做时间搜索框

react如何做时间搜索框

实现时间搜索框的基本步骤 在React中实现时间搜索框通常需要结合日期选择库(如react-datepicker)和状态管理。以下是一个完整的实现示例: 安装依赖库: npm install re…