React-notifications-component,一个强大的React通知库
来自菜鸟教程
在本文中,我们将介绍 react-notifications-component (v2.0.6) 的新版本。 它是一个 React 组件,它为您提供了一个功能齐全的通知系统,可以节省您自己构建一个通知系统的时间和精力。
让我们从安装它和 animate.css 开始:
npm install --save react-notifications-component animate.css
我们使用 animate.css 来制作通知如何进入/退出的动画,但您可以使用任何您喜欢的基于类的动画库。
基本用法
虽然这个库的功能非常丰富,但您可以快速上手,因为设置/配置步骤非常简单:
应用程序.js
import React from 'react';
import ReactNotifications from 'react-notifications-component';
import Homepage from './Homepage';
function App() {
return (
<div>
<ReactNotifications />
<Homepage/>
</div>
);
};
在底层它使用 Context API,所以你只需要在你的应用程序中包含一次,你就可以在任何地方使用它。 您可能希望将 <ReactNotifications /> 放置在应用的顶层附近。
要开始显示通知,请将 store 模块导入任何组件,并使用 store.addNotification() 方法:
主页.js
import React from 'react';
import { store } from 'react-notifications-component';
import 'react-notifications-component/dist/theme.css';
import 'animate.css';
function Homepage() {
return (
<>
My Website
<button
onClick={() => {
store.addNotification({
title: 'Dropbox',
message: 'Files were synced',
type: 'default', // 'default', 'success', 'info', 'warning'
container: 'bottom-left', // where to position the notifications
animationIn: ["animated", "fadeIn"], // animate.css classes that's applied
animationOut: ["animated", "fadeOut"], // animate.css classes that's applied
dismiss: {
duration: 3000
}
})
}}
>
Add notification
</button>
</>
)
}
尝试点击按钮!
注意:如果您在小型设备上查看此通知,您可能会看到全角通知。
包括几种通知类型:成功、警告、信息和默认。
自定义通知
如果你的通知需要自己的 CSS 样式,你实际上可以使用任何有效的 React 元素作为通知!
主页.js
function Homepage() {
return (
<>
My Website
<button
onClick={() => {
store.addNotification({
content: MyNotification,
container: 'bottom-right',
animationIn: ["animated", "fadeIn"],
animationOut: ["animated", "fadeOut"],
dismiss: {
duration: 3000
}
})
}}
>
Add notification
</button>
</>
)
}
MyNotification.js
function MyNotification() {
return (
<div style={{
display: 'flex',
backgroundColor: '#0f2f26',
borderRadius: 5,
}}>
<AlligatorAvatar/>
<div>
<h4>Alligator.io</h4>
<p>Has joined the chat</p>
</div>
</div>
)
}
注意:更多的配置细节可以在文档中找到。
包起来
如果您的 React 应用程序需要通知系统,您绝对应该尝试 react-notifications-component! 有很多功能没有涵盖,包括桌面/移动兼容性、动画选项、触摸手势和响应式设计。