2

我找到了 useToastuseToastContainer,但是没有文档,我不明白你如何使用这些钩子。谁能提供一些关于这些钩子的信息?

4

1 回答 1

1

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

toasts您可以在应用程序中使用两种方法:

1.ToastContainer在组件内部定义

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.在您的应用程序中调用toast.configure()一次。在root您的应用程序中是最好的地方。

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>
    );
  }

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

您可以根据需要添加配置,如下所示:

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>
)
于 2020-07-09T18:26:14.560 回答