React-notifications-component、強力なReact通知ライブラリ

提供:Dev Guides
移動先:案内検索

この記事では、 react-notifications-component (v2.0.6)の新しいリリースについて説明します。 これはReactコンポーネントであり、フル機能の通知システムを提供し、自分で通知システムを構築する時間と労力を節約します。

それをanimate.cssと一緒にインストールすることから始めましょう:

npm install --save react-notifications-component animate.css

通知の出入り方法をアニメーション化するためにanimate.cssを使用していますが、任意のクラスベースのアニメーションライブラリを使用できます。

基本的な使用法

このライブラリは非常に機能が豊富ですが、セットアップ/構成の手順が非常に最小限であるため、非常に迅速に作業を開始できます。

App.js

import React from 'react';
import ReactNotifications from 'react-notifications-component';
import Homepage from './Homepage';

function App() {
  return (
    <div>
      <ReactNotifications />
      <Homepage/>
    </div>
  );
};

内部的にはContextAPI を使用しているため、アプリに1回だけ含める必要があり、どこでも使用できます。 <ReactNotifications />をアプリのトップレベルの近くに配置することをお勧めします。

通知の表示を開始するには、storeモジュールを任意のコンポーネントにインポートし、store.addNotification()メソッドを使用します。

Homepage.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要素を通知として使用できます。

Homepage.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を試してください。 デスクトップ/モバイルの互換性、アニメーションオプション、タッチジェスチャ、レスポンシブデザインなど、カバーされなかった機能がたくさんあります。