当props check为true时如何使用react-toastify内部类组件显示吐司

时间:2020-10-21 04:52:16

标签: javascript reactjs react-toastify

我正在处理react项目,当props(isNotificationOpen)为true时,我试图在div部分中使用react-toastify显示吐司。我尝试了一个类似波纹管的示例,但我不希望在按下按钮时触发吐司,我希望在将isNotificationOpen props设置为true时触发吐司,该如何实现?

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 />
          )} ```

1 个答案:

答案 0 :(得分:2)

使用组件生命周期功能来响应isNotificationOpen道具更改以触发通知。

基于类的组件示例

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

Edit how-to-display-toast-using-react-toastify-inside-class-component-when-props-chec