【问题标题】:Get message id from notistack snackbar从 notistack 小吃店获取消息 ID
【发布时间】:2020-12-26 15:56:24
【问题描述】:

我已经实现了 notistack 小吃栏,但我想阅读小吃栏 onclick 的内容。

const action = key => (
  <Fragment>      
      <Button variant="outline-light" onClick={() => { alert(this.state.notice_id) }}>
          Dismiss
      </Button>
  </Fragment>
);

activeNotices.forEach((element) => {
    this.setState({notice_id: element.notice_id});
    this.props.enqueueSnackbar(element.notice_body + " " + "[" + element.notice_id + "]", { 
      variant: 'warning',
      persist: true,
      action,
      preventDuplicate: true
    }); 

上面的代码只提醒一个通知的notice_id。如何将每个通知与其特定的通知 ID 联系起来?除了在单击关闭按钮时关闭快餐栏之外,我还想获得 notice_id。

【问题讨论】:

    标签: reactjs notistack


    【解决方案1】:

    这里我更新了代码,你需要保留一个通知的ArrayList,并将通知id作为key传递,并从状态中获取其他详细信息。

     const action = key => {
           const notificatification = this.state.notifications.find(noti=>noti.notice_id===key);
         return (
          <Fragment>      
              <Button variant="outline-light" onClick={() => { alert(notificatification.notice_id) }}>
                  Dismiss
              </Button>
          </Fragment>
         )};
        
        activeNotices.forEach((element) => {
          let newnotification = {
            notice_id: element.notice_id,
            messagebody: element.notice_body
        }
        this.setState(prevState => ({
          notifications: [...prevState.notifications, newnotification]
        }))
            //this.setState({notice_id: element.notice_id});
            this.props.enqueueSnackbar( element.notice_id , { 
              variant: 'warning',
              persist: true,
              action,
              preventDuplicate: true
            });
          } 
    

    【讨论】:

    • 实际上我正在寻找将我的 notice_id 变量传递给动作箭头函数的方法。
    • 你想作为另一个属性传递吗?,然后你可以将密钥作为自定义对象传递,例如( {message:your message,noticeid:noticeid} in enquequesnackbar .
    • 请使用此实现更新您的答案。
    • 似乎上面的代码没有执行。然而,我已经更新了我的问题
    • Sam 非常感谢您,但我仍然无法使用您的代码获取 notice_id。如何将你在activeNotices中创建的newnotification对象传递给action函数?
    【解决方案2】:

    想通了

    activeNotices.forEach((element) => {
        const message = element.notice_body;
        this.props.enqueueSnackbar(message, { 
          variant: 'warning',
          persist: true,
          preventDuplicate: true,
          action: key => (
            <Button variant="outline-light"
            onClick={() => { this.props.closeSnackbar(key); this.dissmissNotice(element.notice_id) }}
            >Dismiss
            </Button>
          )          
        });
    

    【讨论】:

      猜你喜欢
      • 2020-05-22
      • 2020-12-24
      • 2019-10-14
      • 2021-06-03
      • 2016-02-06
      • 2020-07-25
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多