Material UI:为什么在 Select 组件上设置背景颜色会隐藏 InputLabel 文本,我该如何避免这种情况发生?

MaterialUI: Why does setting background color on Select component hides the InputLabel text and how could I avoid it happening?

基本上我只是想改变下拉元素的背景颜色,但我也想保留默认文本显示在那里。现在,如果我没有在 Select 组件上显式设置背景颜色,InputLabel 中指定的文本显示得很好,但是一旦我将 style={{backgroundColor: "rgb(232, 241, 250)"}} 添加到 Select,此 InputLabel 文本消失。为什么会发生这种情况,可以采取什么措施来解决这个问题?

代码片段:

<FormControl required fullWidth={true} size="small">
  <InputLabel htmlFor="name" style={{color: "#000"}}>Тема обращения</InputLabel>
  <Select
     variant="filled" 
     style={{backgroundColor: "rgb(232, 241, 250)"}}
     value={props.selectedTheme?.id || ''}
     onChange={(e) => handleChange(e)}>
     {props.themes.map(t => (<MenuItem key={t.id} value={t.id}>{t.name}</MenuItem>))}
  </Select>
</FormControl>

截图:

您应该在 FormControl 元素而不是 Select 元素上指定 variant。将它放在 Select 上后,InputLabel 元素没有获得适合“填充”变体的样式。

这是"filled" style for InputLabel的开头:

  /* Styles applied to the root element if `variant="filled"`. */
  filled: {
    // Chrome's autofill feature gives the input field a yellow background.
    // Since the input field is behind the label in the HTML tree,
    // the input field is drawn last and hides the label with an opaque background color.
    // zIndex: 1 will raise the label above opaque background-colors of input.
    zIndex: 1,

请注意注释表明需要 z-index 才能将标签提升到不透明背景颜色之上(正如您在 Select 上设置的那样)。

这是一个演示 FormControl 上的 variant 的工作示例:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";

const useStyles = makeStyles((theme) => ({
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  }
}));

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

  const handleChange = (event) => {
    setAge(event.target.value);
  };

  return (
    <div>
      <FormControl
        variant="filled"
        size="small"
        className={classes.formControl}
      >
        <InputLabel
          style={{ color: "#000" }}
          id="demo-simple-select-filled-label"
        >
          Age
        </InputLabel>
        <Select
          style={{ backgroundColor: "rgb(232, 241, 250)" }}
          labelId="demo-simple-select-filled-label"
          id="demo-simple-select-filled"
          value={age}
          onChange={handleChange}
        >
          <MenuItem value="">
            <em>None</em>
          </MenuItem>
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
    </div>
  );
}