意外的函数表达式 - 使用通过 Alert 自定义的 MUI Snackbar 组件时出现 ESLint 错误

Unexpected function expression - ESLint error when using MUI Snackbar Component customized with Alert

我想按照官方文档中的示例使用 MUI Alert 创建自定义 MUI Snackbar,但 ESlint 向我显示此错误:

error  Unexpected function expression  prefer-arrow-callback
error  Prop spreading is forbidden     react/jsx-props-no-spreading

这部分代码:

const Alert = React.forwardRef(function Alert(props, ref) {
  return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />;
});

我用 npx eslint . --fix 解决了这个问题,但现在我得到:

error  Component definition is missing display name  react/display-name
error  Prop spreading is forbidden                   react/jsx-props-no-spreading

这是我的全部 code:

import * as React from 'react';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Snackbar from '@mui/material/Snackbar';
import MuiAlert from '@mui/material/Alert';

const Alert = React.forwardRef(function Alert(props, ref) {
  return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />;
});

export default function CustomizedSnackbars() {
  const [open, setOpen] = React.useState(false);

  const handleClick = () => {
    setOpen(true);
  };

  const handleClose = (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }

    setOpen(false);
  };

  return (
    <Stack spacing={2} sx={{ width: '100%' }}>
      <Button variant="outlined" onClick={handleClick}>
        Open success snackbar
      </Button>
      <Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
        <Alert onClose={handleClose} severity="success" sx={{ width: '100%' }}>
          This is a success message!
        </Alert>
      </Snackbar>
    </Stack>
  );
}

这些是你的 eslint 错误

error  Unexpected function expression  prefer-arrow-callback
error  Prop spreading is forbidden     react/jsx-props-no-spreading
error  Component definition is missing display name  react/display-name

prefer-arrow-callback: 在forward

中使用这个=>

const Alert = React.forwardRef((props, ref) => {
  return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />;
});

react/display-name

const Alert = () => {
  .... 
}
Alert.displayName = "Alert";

react/jsx-props-no-spreading

如果您不想禁用它,您将必须列出所有 MuiAlert 道具并将其传递给

const Alert = React.forwardRef((props, ref) => {
  const {
    action,
    children,
    classes,
    closeText,
    color,
    icon,
    iconMapping ,
    onClose,
    event,
    role,
    severity,
    sx,
    variant = "filled,
  } = props;
  return <MuiAlert ref={ref} elevation={6} variant={variant} action={action} ... />;
});