如何样式化材质-UI选择

时间:2020-07-19 15:02:38

标签: reactjs material-ui styled-components

我需要制作material-ui select组件的样式化版本。 我现在拥有的是:

import { Select } from '@material-ui/core';
import type { SelectProps } from '@material-ui/core';
import styled from 'styled-components';


const menuProps = {
    getContentAnchorEl: null,
    anchorOrigin: {
        vertical: "bottom",
        horizontal: "left",
    },

    PopoverClasses: {
        // pass only classnames
    }
}

const StyledSelect = styled(Select)<SelectProps>`
   ... some styles
`;

const Select: React.FC<SelectProps> = (props) => {
    return <StyledSelect MenuProps={menuProps} {...props}/>
};

我需要将样式(NOT CLASSES)传递给Select的popover部分,以使popover和input之间有一个边距。 我尝试了一切,并找到了将类传递给他们的唯一方法。 但是由于项目限制,我不能使用全局类或模块类,只能在js中传递它们。 有任何想法吗? example of required changes

1 个答案:

答案 0 :(得分:1)

如果使用disablePortal: true菜单道具,它将导致Popover是DOM中Select根元素的后代。这样您就可以将其定位为以下目标:

const Select = styled(MuiSelect)`
  .MuiPopover-paper {
    margin-top: 3px;
  }
`;

这是一个完整的示例:

import React from "react";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import MuiFormControl from "@material-ui/core/FormControl";
import MuiSelect from "@material-ui/core/Select";
import styled from "styled-components";
import { StylesProvider } from "@material-ui/core/styles";

const FormControl = styled(MuiFormControl)`
  margin: 8px;
  min-width: 120px;
`;
const Select = styled(MuiSelect)`
  .MuiPopover-paper {
    margin-top: 3px;
  }
`;

export default function SimpleSelect() {
  const [age, setAge] = React.useState("");

  const handleChange = event => {
    setAge(event.target.value);
  };
  const menuProps = {
    getContentAnchorEl: null,
    anchorOrigin: {
      vertical: "bottom",
      horizontal: "left"
    },
    disablePortal: true
  };
  return (
    <StylesProvider injectFirst>
      <div>
        <FormControl>
          <InputLabel id="demo-simple-select-label">Age</InputLabel>
          <Select
            labelId="demo-simple-select-label"
            id="demo-simple-select"
            value={age}
            onChange={handleChange}
            MenuProps={menuProps}
          >
            <MenuItem value={10}>Ten</MenuItem>
            <MenuItem value={20}>Twenty</MenuItem>
            <MenuItem value={30}>Thirty</MenuItem>
          </Select>
        </FormControl>
      </div>
    </StylesProvider>
  );
}

Edit styled Select popover paper