Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【Q038】使用 react 实现一个通用的 message 组件 #39

Open
shfshanyue opened this issue Nov 18, 2019 · 2 comments
Open

【Q038】使用 react 实现一个通用的 message 组件 #39

shfshanyue opened this issue Nov 18, 2019 · 2 comments
Labels

Comments

@shfshanyue
Copy link
Owner

No description provided.

@shfshanyue shfshanyue changed the title 【Q038】使用 react 如何实现一个通用的 message 组件 【Q038】使用 react 实现一个通用的 message 组件 Nov 18, 2019
@HXML
Copy link

HXML commented Aug 10, 2022

这个没人回答的吗

@stillsailing
Copy link

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
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants