You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何在单个Toast内实现多条消息拼接展示?

在React中实现可拼接消息的单Toast组件

核心逻辑是维护一个消息数组状态,每次新增消息时将其追加到数组中而非替换原有内容;Toast组件则根据这个数组渲染所有消息,实现同一Toast内的消息拼接效果。

实现步骤与代码示例

1. 自定义Toast组件

这个组件负责接收消息列表、渲染所有消息,并提供关闭功能:

// Toast.jsx
import './Toast.css';

export default function Toast({ messages, onClose }) {
  return (
    <div className="toast-container">
      <button className="toast-close-btn" onClick={onClose}>×</button>
      <div className="toast-content">
        {messages.map((msg, idx) => (
          <p key={idx} className="toast-message">{msg}</p>
        ))}
      </div>
    </div>
  );
}

对应的基础样式(Toast.css):

.toast-container {
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  background-color: #2d3748;
  color: #fff;
  padding: 1rem 1.5rem;
  border-radius: 0.5rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-width: 280px;
}

.toast-close-btn {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  background: transparent;
  border: none;
  color: #fff;
  font-size: 1.2rem;
  cursor: pointer;
}

.toast-message {
  margin: 0.3rem 0;
  font-size: 0.9rem;
}

2. 父组件中维护消息状态并控制Toast

在需要使用Toast的组件中,通过useState维护消息数组和Toast的显隐状态,同时提供添加消息的方法:

// App.jsx
import { useState } from 'react';
import Toast from './Toast';

export default function App() {
  const [toastMessages, setToastMessages] = useState([]);
  const [showToast, setShowToast] = useState(false);
  let toastTimer = null;

  // 添加消息逻辑:支持传入单条字符串或字符串数组
  const addToToast = (newMessages) => {
    // 将新消息追加到原有列表中
    setToastMessages(prev => [
      ...prev,
      ...(Array.isArray(newMessages) ? newMessages : [newMessages])
    ]);
    setShowToast(true);

    // 重置自动关闭定时器:最后一条消息添加后,5秒后关闭Toast
    if (toastTimer) clearTimeout(toastTimer);
    toastTimer = setTimeout(() => {
      setToastMessages([]);
      setShowToast(false);
    }, 5000);
  };

  // 手动关闭Toast
  const closeToast = () => {
    setToastMessages([]);
    setShowToast(false);
    if (toastTimer) clearTimeout(toastTimer);
  };

  return (
    <div className="app-container">
      <button onClick={() => addToToast(['消息1', '消息2', '消息3'])}>
        弹出初始3条消息
      </button>
      <button onClick={() => addToToast('后续追加的单条消息')}>
        追加单条消息
      </button>
      <button onClick={() => addToToast(['追加消息A', '追加消息B'])}>
        追加多条消息
      </button>

      {showToast && <Toast messages={toastMessages} onClose={closeToast} />}
    </div>
  );
}

扩展说明

  • 消息类型扩展:如果需要区分消息类型(如成功、错误、警告),可以将消息改为对象数组,例如{ text: '操作成功', type: 'success' },然后在Toast组件中根据type渲染不同的样式。
  • 全局Toast:如果需要在应用多个组件中调用Toast,可以使用React Context封装Toast的状态和添加方法,实现全局调用。
  • 防抖优化:如果短时间内频繁添加消息,上述逻辑会自动重置定时器,保证Toast在最后一次操作后再停留指定时长。

内容的提问来源于stack exchange,提问作者nanda yelgar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 01:42:10