Объекты toasts
наследуют ToastContainer’s
props. Свойства, определенные в тосте, заменяют свойства 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>
);
}
Вы можно использовать любой из них. Я предпочитаю метод 2nd , потому что вам нужно только определить toast.configure()
, что является довольно чистым способом его добавления.
Вы можете добавить конфигурацию в соответствии с вашими потребностями, как показано ниже:
toast.configure({
autoClose: 8000,
draggable: false,
//etc you get the idea
});
EDIT
Если вы хотите использовать перехватчики тостов, вы должны обернуть свое приложение 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>
)