我找到了 useToast 和 useToastContainer,但是缺少文档,我不明白如何使用这些 Hook 。任何人都可以提供有关这些 Hook 的一些信息吗?
最佳答案
toasts
继承了 ToastContainer 的
属性。在 toast 上定义的 Prop 取代了 ToastContainer 的 Prop 。
您可以通过两种方式在您的应用程序中使用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 theroot
of your app is the best place.
如果没有挂载,该库将为您挂载一个 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 Hook ,则必须使用 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>
)
关于reactjs - 我如何使用 hook 中的 react-toastify?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62820758/