reactjs 选择物料组件Ui未显示其标签

nnsrf1az  于 2023-01-04  发布在  React
关注(0)|答案(3)|浏览(149)

选择物料Ui的组件 (下拉) 未显示其标签

<Select
                         labelId="demo-simple-select-label"
                         id="demo-simple-select"
                         value={role}
                         label="Role"
                        size='small'
                        sx={{ width: '90%', marginBottom: '1rem' }}
                    >
                        <MenuItem value= 'MVD'>MVD</MenuItem>
                        <MenuItem value= 'Police'>Police</MenuItem>
                        <MenuItem value= 'Coperation'>Coperation</MenuItem>
                    </Select>

我期待的结果与上图类似
如果你能帮我解决这个简单的错误,我将不胜感激

rlcwz9us

rlcwz9us1#

嗨@Git·阿达夏,

有很多事情需要注意,选择MenuItem时需要修改Role状态变量的值。

function App() {
  const [Role, setRole] = useState("MVD");
  return (
    <>
      <Select
        labelId="demo-simple-select-label"
        id="demo-simple-select"
        value={Role}       // here we are using the Role state.
        label="Role"
        size="small"
        onChange={(event) => setRole(event.target.value)} //update the Role state
        sx={{ width: "90%", marginBottom: "1rem" }}
      >
        <MenuItem value="MVD">MVD</MenuItem>
        <MenuItem value="Police">Police</MenuItem>
        <MenuItem value="Coperation">Coperation</MenuItem>
      </Select>
    </>
  );
}

onchange事件使用setRole函数用将要选择的新值更新角色状态。

下面是演示:-codesandbox

oknrviil

oknrviil2#

import * as React from "react";
import Box from "@mui/material/Box";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";
import { makeStyles } from "@mui/styles";

const usePlaceholderStyles = makeStyles((theme) => ({
  placeholder: { color: "#a3a3a3" }
}));

const Placeholder = ({ children }) => {
  const classes = usePlaceholderStyles();
  return <div className={classes.placeholder}>{children}</div>;
};

export default function BasicSelect() {
  const [role, setRole] = React.useState("");
  return (
    <Box sx={{ minWidth: 120 }}>
      <FormControl fullWidth>
        <Select
          fullWidth
          size="small"
          value={role}
          displayEmpty
          onChange={(event) => setRole(event.target.value)}
          renderValue={
            role !== "" ? undefined : () => <Placeholder>Role</Placeholder>
          }
        >
          <MenuItem value="MVD">MVD</MenuItem>
          <MenuItem value="Police">Police</MenuItem>
          <MenuItem value="Coperation">Coperation</MenuItem>
        </Select>
      </FormControl>
    </Box>
  );
}
o8x7eapl

o8x7eapl3#

我已经研究了很多,并找到了确切的输出,我所期望的

<TextField
          variant="outlined"
          value={role}
          select
          label="Role"
          onChange={handleChange}
          sx={{ width: '90%', marginBottom: '1rem' }}
        >
          <MenuItem value='student'>Student</MenuItem>
          <MenuItem value='public'>Public</MenuItem>
        </TextField>

相关问题