使用 react 实现一个通用的 message 组件
Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 39
Author 回答者: HXML
这个没人回答的吗
Author 回答者: stillsailing
import * as React from "react";
import { createRoot } from "react-dom/client";
const root = createRoot(getRootDOM());
let timer: NodeJS.Timeout;
interface ToastOpts {
message: string;
duration?: number;
}
export default function showToast(options: ToastOpts) {
const { message, duration = 3000 } = options;
const $Toast = (
<div className="toast toast-top toast-center">
<span>{message}</span>
</div>
);
root.render($Toast);
clearTimeout(timer);
timer = setTimeout(() => root.render(null), duration);
}
function getRootDOM() {
const rootId = "notification-root";
let root: HTMLElement = window[rootId] || document.getElementById(rootId);
if (!root) {
root = document.createElement("div");
root.id = rootId;
document.body.appendChild(root);
window[rootId] = root;
}
return root;
}
Author 回答者: fantiyun
import React, { useEffect } from 'react';
import './Message.css'; // 引入样式文件
const Message = ({ message, type, duration = 3000, onClose }) => {
useEffect(() => {
const timer = setTimeout(() => {
if (onClose) {
onClose();
}
}, duration);
return () => clearTimeout(timer);
}, [duration, onClose]);
return (
<div className={`message ${type}`}>
{message}
<button className="close-button" onClick={onClose}>×</button>
</div>
);
};
export default Message;
Author 回答者: loveminxo
这是来自QQ邮箱的假期自动回复邮件。你好,我最近正在休假中,无法亲自回复你的邮件。我将在假期结束后,尽快给你回复。