繁体   English   中英

MUI选择带有标签,但选择没有ID

[英]MUI select with label without the select having an ID

我在可能多次出现在页面中的组件中有材料ui react select。

示例中,所有标记为select的选择都将InputLabel与htmlFor一起使用,该对象必须是select的ID。

我无法提供选择ID,因为ID必须是页面的唯一ID,并且这是一个不需要知道页面上所有ID的组件(我的代码中的任何地方都不想知道ID中的所有ID)这一页)。

根据InputLabel文档,它甚至没有文档化的htmlFor属性。

是否可以在不提供ID的情况下标记MUI选择?

只要您在嵌套解决方案中不会遇到任何样式方面的困难,那就完全可以了,但这是一个使用生成的ID的示例,该示例将使您避免将Select嵌套在InputLabel中:

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";

let nextIdSuffix = 1;

const useStyles = makeStyles(theme => ({
  root: {
    display: "flex",
    flexWrap: "wrap"
  },
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  }
}));

const CustomSelect = () => {
  const idRef = React.useRef();
  const classes = useStyles();
  const [value, setValue] = React.useState("");
  if (!idRef.current) {
    idRef.current = `CustomSelect${nextIdSuffix}`;
    nextIdSuffix++;
  }
  return (
    <FormControl className={classes.formControl}>
      <InputLabel htmlFor={idRef.current}>Age</InputLabel>
      <Select
        value={value}
        onChange={e => setValue(e.target.value)}
        inputProps={{
          name: idRef.current,
          id: idRef.current
        }}
      >
        <MenuItem value={10}>Ten</MenuItem>
        <MenuItem value={20}>Twenty</MenuItem>
        <MenuItem value={30}>Thirty</MenuItem>
      </Select>
    </FormControl>
  );
};
export default CustomSelect;

编辑生成的选择ID

html标签相同; 我在InputLabel中嵌套了Select:

<InputLabel className="paging">
  Page:
  <Select
    value={current}
    onChange={e => changePage(e.target.value)}
    inputProps={{
      name: 'page',
      id: 'page',
    }}
  >
    {options.map(option => (
      <MenuItem key={option} value={option}>
        {option}
      </MenuItem>
    ))}
  </Select>
</InputLabel>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM