我如何使用 hook 中的 react-toastify?

How can i use react-toastify from hook?

我找到了 useToastuseToastContainer,但是没有文档,我不明白你是如何使用这些钩子的。任何人都可以提供有关这些挂钩的一些信息吗?

toasts继承ToastContainer’s道具。在 toast 上定义的道具取代了 ToastContainer 的道具。

您可以通过两种方式在您的应用程序中使用 toasts

1. Define ToastContainer inside the component

import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
  
  const App = () => {
    notify = () => toast("Wow so easy !");

    return (
      <div>
        <button onClick={notify}>Notify !</button>

        // You can add <ToastContainer /> in root component as well.
        <ToastContainer />
      </div>
    );
  }

2. Call toast.configure() once in your app. At the root of your app is the best place.

如果安装了 none,库将为您安装一个 ToastContainer

import { toast } from "react-toastify";
import 'react-toastify/dist/ReactToastify.css';
  
   // Call it once in your app. At the root of your app is the best place
  toast.configure()
  
  const App = () => {
    notify = () => toast("Wow so easy !");

    return (
        <button onClick={notify}>Notify !</button>
    );
  }

您可以使用其中任何一个。我更喜欢 2nd 方法,因为你只需要定义 toast.configure() ,这是一种非常干净的添加方法。

You can add configuration as per your need like below:

toast.configure({
  autoClose: 8000,
  draggable: false,
  //etc you get the idea
});

编辑

如果您想使用 toast 挂钩,则必须使用 ToastProvider 包装您的应用程序,以便在应用程序的其他地方访问它的上下文。

import { ToastProvider, useToasts } from 'react-toast-notifications'

const FormWithToasts = () => {
  const { addToast } = useToasts()

  const onSubmit = async value => {
    const { error } = await dataPersistenceLayer(value)

    if (error) {
      addToast(error.message, { appearance: 'error' })
    } else {
      addToast('Saved Successfully', { appearance: 'success' })
    }
  }

  return <form onSubmit={onSubmit}>...</form>
}

const App = () => (
  <ToastProvider>
    <FormWithToasts />
  </ToastProvider>
)