如何覆盖材料UI组件中的特定样式

时间:2020-02-26 12:22:49

标签: reactjs material-ui

我正在使用MUI中的组件, 当我使用开发工具时,我可以看到它具有以下样式:

.MuiList-padding {
    padding-top: 8px;
    padding-bottom: 8px;
}

我希望删除填充物,但无法正常工作, 我尝试过

  <Menu
        id="simple-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={closeMenu}
        styles={{MuiList:{{padding:none}}}} 
      >
        <somecomponent/>
      </Menu>

但是没有运气,有什么想法吗?

2 个答案:

答案 0 :(得分:1)

使用makeStylesMuiList-Padding定义新样式,然后使用useStyles钩子和MuiListProps属性覆盖该样式:

import React from 'react';
import Button from '@material-ui/core/Button';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import { makeStyles } from "@material-ui/core/styles";


const useStyles = makeStyles(theme => ({
  padding: {
    paddingTop: "30px",
    paddingBottom: "30px"
  }
}));

export default function SimpleMenu() {
  const [anchorEl, setAnchorEl] = React.useState(null);
  const classes = useStyles();

  const handleClick = event => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  return (
    <div>
      <Button aria-controls="simple-menu" aria-haspopup="true" onClick={handleClick}>
        Open Menu
      </Button>
      <Menu
        id="simple-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
        MenuListProps={{
          classes: {padding: classes.padding},
        }}
      >
        <MenuItem onClick={handleClose}>Profile</MenuItem>
        <MenuItem onClick={handleClose}>My account</MenuItem>
        <MenuItem onClick={handleClose}>Logout</MenuItem>
      </Menu>
    </div>
  );
}

您可以检查Code Sandbox link正常工作


注意:此答案适用于Material-ui V4

答案 1 :(得分:1)

List有一个disablePadding道具(https://material-ui.com/api/list/#props)。

您可以通过MenuMenuListProps进行设置,如下所示:

import React from "react";
import Button from "@material-ui/core/Button";
import Menu from "@material-ui/core/Menu";
import MenuItem from "@material-ui/core/MenuItem";

export default function SimpleMenu() {
  const [anchorEl, setAnchorEl] = React.useState(null);

  const handleClick = event => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  return (
    <div>
      <Button
        aria-controls="simple-menu"
        aria-haspopup="true"
        onClick={handleClick}
      >
        Open Menu
      </Button>
      <Menu
        id="simple-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
        MenuListProps={{
          disablePadding: true
        }}
      >
        <MenuItem onClick={handleClose}>Profile</MenuItem>
        <MenuItem onClick={handleClose}>My account</MenuItem>
        <MenuItem onClick={handleClose}>Logout</MenuItem>
      </Menu>
    </div>
  );
}

Edit Menu disablePadding

相关答案: