javascript - 当道具检查为真时,如何在类组件内使用 react-toastify 显示 toast
问题描述
我正在研究反应项目,我试图在道具( isNotificationOpen )为真时在 div 部分中使用 react-toastify 显示吐司。我尝试了一个类似下面的示例,但我不希望在按下按钮时触发 toast,我希望在 isNotificationOpen 道具设置为 true 时触发 tost,我该如何实现?
const notify = () => toast("Wow so easy !");
render() {
return (
<div className="d-flex" style={{ margin: "25px" }}>
<div className="mr-auto p-2">
{this.props.isNotificationOpen ? (
<div>
<div>
<button onClick={notify}>Notify !</button>
<ToastContainer />
</div>
//Show toast here...
</div>
) : (
<p />
)} ```
解决方案
使用组件生命周期函数来响应isNotificationOpen
prop 更改以触发通知。
基于类的组件示例
notify = () => toast('Wow so easy!');
componentDidMount() {
const { isNotificationOpen } = this.props;
isNotificationOpen && this.notify();
}
componentDidUpdate(prevProps) {
const { isNotificationOpen } = this.props;
if (prevProps.isNotificationOpen !== isNotificationOpen) {
isNotificationOpen && this.notify();
}
}
功能组件示例
useEffect(() => {
props.isNotificationOpen && toast('Wow so easy!');
}, [props.isNotificationOpen]);
推荐阅读
- amazon-web-services - AWS Timestream:无法将记录摄取到 AWS Timestream
- c - 使用 Doxygen 创建 Graphviz 图时出错
- r - R中的数值微分
- r - 有什么作用。(点)在 ~replace_na(., 0) 中的意思
- postgresql - Postgres - 复制命令
- c - 需要 memset 全局字符串或全局结构中的字符串
- laravel - Laravel 和上传图片超过 2MB
- python - NumPy - 检查数组是否是另一个数组的视图的最快方法
- sql - 在 MSSQL 中使用 STRING_ESCAPE 时保持回车/换行
- c++ - 使用 QUdpSocket 从特定地址接收数据