当前位置:首页 > 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:

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:

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;
  }
}

react如何做toast提示

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

相关文章

vue实现搜索提示

vue实现搜索提示

Vue实现搜索提示的方法 使用Vue实现搜索提示功能可以通过以下几种方式实现: 使用v-model和计算属性 在Vue组件中绑定输入框的v-model,通过计算属性过滤匹配的数据。 <te…

vue实现消息提示

vue实现消息提示

Vue 实现消息提示的方法 在 Vue 中实现消息提示功能可以通过多种方式完成,以下是几种常见的实现方法。 使用 Vue 插件(如 Element UI、Vant 等) Element UI 提供了…

vue实现更新提示

vue实现更新提示

实现更新提示的基本思路 在Vue中实现更新提示通常需要结合版本检测和用户交互逻辑。核心是通过对比本地版本与远程版本,当检测到新版本时触发提示机制。 版本检测方法 使用package.json中的版…

vue实现提示组件

vue实现提示组件

Vue 实现提示组件的方法 使用 Vue 原生方式创建 创建一个基础的提示组件,可以通过 v-if 或 v-show 控制显示状态,并通过 props 传递消息内容和类型。 <template…

vue实现下载提示

vue实现下载提示

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

vue实现搜索框提示

vue实现搜索框提示

实现搜索框提示功能 在Vue中实现搜索框提示功能通常需要结合输入框监听、数据过滤和展示逻辑。以下是具体实现方法: 监听输入框变化 使用v-model绑定输入框的值,并监听输入变化: <t…