react 全局notification怎么写
时间: 2023-08-14 19:02:56 浏览: 64
在 React 中实现全局通知(notification)可以使用第三方库,比如 react-toastify 或 react-notification-system。下面是一个使用 react-toastify 的示例:
1. 首先,安装 react-toastify:
```shell
npm install react-toastify
```
2. 在你的组件中导入 react-toastify:
```jsx
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
// ...
// 在组件的最外层添加 ToastContainer 组件
const App = () => {
return (
<div>
{/* 其他组件 */}
<ToastContainer />
</div>
);
};
```
3. 呈现全局通知:
```jsx
// 在需要触发通知的地方调用 toast 方法
const handleClick = () => {
toast('Hello, world!');
};
// ...
<button onClick={handleClick}>显示通知</button>
```
通过调用 `toast` 方法,你可以显示一个简单的通知消息。你还可以传递其他选项来自定义通知的外观和行为。你可以在 react-toastify 的文档中找到更多用法和选项。
这只是使用 react-toastify 的一个基本示例,你可以根据你的需求进行自定义和扩展。