【问题标题】:MUI select with label without the select having an ID带有标签的 MUI 选择,而选择没有 ID
【发布时间】:2019-11-08 09:20:21
【问题描述】:

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

examples 中,所有带标签的选择都使用 InputLabel 和 htmlFor,它必须是选择的 id。

我不能给选择一个 id,因为 id 对于页面来说必须是唯一的,而且这是一个不需要知道页面上所有 id 的组件(我也不想在我的代码中的任何地方知道所有id 在页面中)。

根据InputLabel documentation,它甚至没有记录在案的 htmlFor 属性。

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

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    只要您的嵌套解决方案没有遇到任何样式问题,那就完全没问题了,但这里有一个使用生成的 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;
    

    【讨论】:

      【解决方案2】:

      html label tag;我在 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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-10
        • 2019-05-15
        • 1970-01-01
        • 1970-01-01
        • 2019-10-18
        • 1970-01-01
        相关资源
        最近更新 更多