Mui V5 Snackbar 自定义位置

问题描述 投票:0回答:4

我试图将 Snackbar 定位到右上角并进行一些 top: 自定义,但我无法正确设置它。

这是我的尝试:

import React from "react";
import { Snackbar, Alert } from "@mui/material";

import { styled } from "@mui/material/styles";
const StyledSnackbar = styled(Snackbar)(({ theme, props }) => ({
  "& MuiSnackbar-root": {
    top: theme.spacing(15),
  },
}));

export default function Notification(props) {
  const { notify, setNotify } = props;
  return (
    <StyledSnackbar
      open={notify.isOpen}
      autoHideDuration={3000}
      anchorOrigin={{ vertical: "top", horizontal: "right" }}
    >
      <Alert severity={notify.type}>{notify.message}</Alert>
    </StyledSnackbar>
  );
}

然后我尝试了

const StyledSnackbar = styled(Snackbar)(() => ({
  "& MuiSnackbar-root": {
    top: "100px",
  },
}));

但还是不行,Snackbar 固定在顶部/右侧

javascript reactjs typescript material-ui
4个回答
1
投票

看起来不像

Snackbar
组件提供任何精确定位的方法,除了相当有限的
anchorOrigin
之外。

它的根元素使用

position: fixed
因此用正确样式的
<Portal>
包装它也没有帮助。

负责定位的组件源码


0
投票

我终于弄清楚了,但我不确定这是否是实现它的最佳方法。请让我知道你的想法?以及是否有更好的方法。

import React from "react";
import { Snackbar, Alert } from "@mui/material";

import { styled } from "@mui/material/styles";

const StyledSnackbar = styled((props) => <Snackbar {...props} />)(
  ({ theme }) => ({
    "& .MuiSnackbar-root": {
      top: theme.spacing(15),
    },
  })
);

export default function Notification(props) {
  const { notify, setNotify } = props;
  return (
    <StyledSnackbar
      open={notify.isOpen}
      autoHideDuration={3000}
      anchorOrigin={{ vertical: "top", horizontal: "right" }}
    >
      <Alert severity={notify.type}>{notify.message}</Alert>
    </StyledSnackbar>
  );
}

0
投票

这是我的方法,它似乎与 MUI v5 配合得很好。我已经重写了 MuiSnackbar-root 类以具有不同的底部值。您可以根据需要对顶部、左侧和右侧执行相同的操作。

    <Snackbar
      open={open}
      autoHideDuration={timeout * 1000}
      onClose={handleClose}
      sx={{
        '&.MuiSnackbar-root': { bottom: '50px' },
      }}
    >
      <SnackbarContent
        sx={{ backgroundColor: '#bb4420' }}
        message={message}
        action={action}
      />
    </Snackbar>

-2
投票

我在 stylesheet.css 中使用它

.MuiSnackbar-anchorOriginTopCenter {
  top: 150px !important;
}
© www.soinside.com 2019 - 2024. All rights reserved.