首页 > 解决方案 > 如何样式化material-ui select

问题描述

我需要制作一个风格化版本的 material-ui 选择组件。我现在拥有的是:

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 的弹出框部分,以在弹出框和输入之间留出余量。我尝试了一切,并找到了将课程传给他们的唯一方法。但是由于项目限制,我不能使用全局类或模块类,只能在js中传递它们。有任何想法吗? 所需更改的示例

标签: reactjsmaterial-uistyled-components

解决方案


如果你使用disablePortal: truemenu 属性,它会导致PopoverDOM 成为 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>
  );
}

编辑样式选择弹出纸


推荐阅读