iT邦幫忙

1

React 學習筆記_16(React Toastify彈出組件)

React Toastify彈出組件

簡介

使用React-Toastify來達成簡易的彈出效果。

Step 1: Installation

npm install --save react-toastify
yarn add react-toastify

Step 2: Import ToastContainer / CSS

  • Remember to render the ToastContainer once in your application tree. If you can't figure out where to put it, rendering it in the application root would be the best bet.
  • 記得要在application tree中render一次ToastContainer,如果不知道該把ToastContainer放在哪,將它放在最頂層是最好的方法。
import React from "react";
import ReactDOM from "react-dom";
import APP from "./APP";
import { ToastContainer } from 'react-toastify'; //ToastContainer
import 'react-toastify/dist/ReactToastify.css'; //CSS Style

ReactDOM.render(<div>
                    <APP />
                    <ToastContainer /> 
                </div>
,document.getElementById("root"));

Step 3: 到React Toastify選擇彈出組件的樣式

可以到React Toastify選擇彈出組件的樣式。
https://ithelp.ithome.com.tw/upload/images/20200406/20124767VeXdHvouTw.png

Step 4: 將選擇好的樣式貼到 ToastContainer 中

ReactDOM.render(<div>
                    <APP />
                    <ToastContainer 
                        //將選擇的樣式貼上
                        position="top-right"
                        autoClose={2000}
                        newestOnTop={false}
                        closeOnClick
                        rtl={false}
                        pauseOnVisibilityChange
                        draggable 
                    />
                </div>
,document.getElementById("root"));

Step 5: 將toast Import 到需要的Component中

import React from "react";
import { toast } from 'react-toastify'; //import toast

class APP extends React.Component
{
    //按鈕被點擊時觸發
    handleClick = () => {
        toast.success("Toast Success!!");
        toast.error("Toast Error!!");
    };

    render()
    {
        return(
            <div>
                <button onClick={this.handleClick}>Click</button>
            </div>
        );
    }
}

export default APP;

結果 :
結果

參考資料 :
React Toastify GitHub


尚未有邦友留言

立即登入留言