首页 > 解决方案 > 当道具检查为真时,如何在类组件内使用 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 />
          )} ```

标签: javascriptreactjsreact-toastify

解决方案


使用组件生命周期函数来响应isNotificationOpenprop 更改以触发通知。

基于类的组件示例

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

编辑 how-to-display-toast-using-react-toastify-inside-class-component-when-props-check


推荐阅读