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

She*_*neh 5 reactjs material-ui

尝试将 Material UI 选择组件与 FormControl 和 InputLabel 一起使用时,选择的标签始终呈现在选择组件上方,我不知道为什么。

我的代码看起来像这样

 <FormControl>
      <InputLabel htmlFor="hey">A Label</InputLabel>
      <Select inputProps={{
         id: "hey"
      }} value="Hey">
          <MenuItem value="Hey">
             Hey
          </MenuItem>
      </Select>
   </FormControl>
Run Code Online (Sandbox Code Playgroud)

Rya*_*ell 4

如果当前选定的选项具有空值,则标签只会位于选择框中;否则,它需要显示所选项目,并且标签必须向上移开。在您的示例中,您的“选择”中只有一个值为“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);

Run Code Online (Sandbox Code Playgroud)

编辑带标签的选择