繁体   English   中英

什么可能导致 MUI Snackbar 无法生成正确的 class 名称?

[英]What might cause an MUI Snackbar to not generate the correct class names?

当服务工作者更新时,我正在尝试使用MUI Snackbar toast在我的 Gatsby 博客上显示通知。 有时吐司没有任何样式,看起来像这样:

没有风格的小吃店

它应该如下所示:

正确的小吃店吐司

我可以看到<Snackbar>MUIAlert没有 output 在他们的div上正确的类。

代码如下:

export default function Layout({ children }: { children: ReactNode }): ReactElement {
  const [toastOpenState, setToastOpenState] = React.useState(isBrowser() && Boolean(localStorage.getItem('serviceWorkerUpdated')));

  function handleToastClose(): void {
    setToastOpenState(false);
  }

  return (
    <>
      <TopNav/>

      <Snackbar className="toast"
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
        open={toastOpenState}
        onClose={handleToastClose}
        TransitionComponent={Transition}
      >
        <MuiAlert severity="success" variant="filled" elevation={6} onClose={handleToastClose}>
          A new version is available.
          <Button onClick={() => {
            localStorage.removeItem('serviceWorkerUpdated');
            window.location.reload();
          }}>Reload</Button>
        </MuiAlert>
      </Snackbar>

      <div style={{ flex: 1, margin: '0 1em' }}>
        {children}
      </div>
      <Footer />
    </>
  );
}

解决方案是将 toast 的open state 从onEffect挂钩设置为true

  const [toastOpenState, setToastOpenState] = React.useState(false);
  useEffect(() => {
    if (localStorage.getItem('serviceWorkerUpdated'))
      setToastOpenState(true);
  }, []);

  // Called by clicking the close button
  function handleToastClose(): void {
    setToastOpenState(false);
  }

  return (
    <>
      ... same stuff
    </>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM