出现在组件上方的 Material UI Select 按钮标签

IT技术 reactjs material-ui
2021-05-22 13:59:57

尝试使用带有 FormControl 和 InputLabel 的 Material UI 选择组件时,选择的标签总是呈现在选择组件上方,我不知道为什么。

我的代码看起来像这样

 <FormControl>
      <InputLabel htmlFor="hey">A Label</InputLabel>
      <Select inputProps={{
         id: "hey"
      }} value="Hey">
          <MenuItem value="Hey">
             Hey
          </MenuItem>
      </Select>
   </FormControl>
2个回答

如果当前选择的选项为空值,则标签只会位于选择框中;否则它需要显示选定的项目,并且标签必须不碍事。在您的示例中,您的 Select 中只有一个值为“Hey”的选项,因此它将开始被选中并显示。

这是一个示例并排显示您的示例Select和一个以选择的空值开头的示例

import React, { useState } from "react";
import ReactDOM from "react-dom";

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

const styles = theme => ({
  formControl: {
    margin: theme.spacing.unit,
    minWidth: 120
  }
});

function App({ classes }) {
  const [value, setValue] = useState("");
  return (
    <>
      <FormControl className={classes.formControl}>
        <InputLabel htmlFor="hey">A Label</InputLabel>
        <Select
          inputProps={{
            id: "hey"
          }}
          value="Hey"
        >
          <MenuItem value="Hey">Hey</MenuItem>
        </Select>
      </FormControl>
      <FormControl className={classes.formControl}>
        <InputLabel htmlFor="hey2">A Label</InputLabel>
        <Select
          inputProps={{
            id: "hey2"
          }}
          value={value}
          onChange={event => setValue(event.target.value)}
        >
          <MenuItem value="">Empty Value for First Option</MenuItem>
          <MenuItem value="Hey">Hey</MenuItem>
        </Select>
      </FormControl>
    </>
  );
}
const StyledApp = withStyles(styles)(App);
const rootElement = document.getElementById("root");
ReactDOM.render(<StyledApp />, rootElement);

编辑标签选择

我在使用 material-ui 时遇到了这个问题v3.9.2我更新到最新版本(当前v4.5.0)并为我修复了它。