【问题标题】:Dropdown menu with Material UI and Hooks doesn't work带有 Material UI 和 Hooks 的下拉菜单不起作用
【发布时间】:2019-12-30 06:01:16
【问题描述】:

我正在尝试使用 React Hooks 和 Material UI 创建一个简单的选择标签,但不知道如何设置菜单中所选项目的值。

我设法从 hooks 数组中获取菜单项,但一旦我选择一个,代码就会中断。

const [values, setValues] = React.useState([
    "Bam",
    "Kate",
    "Nicole",
    "Aaron"
  ]);

  function handleChange(event) {
    setValues(oldValues => ({
      ...oldValues,
      [event.target.value]: event.target.value
    }));
  }
            <FormControl className={classes.formControl}>
              <InputLabel htmlFor="agent-simple">Agent</InputLabel>
              <Select
                value={values.value}
                onChange={handleChange}
                inputProps={{
                  name: "agent",
                  id: "age-simple"
                }}
              >
                {values.map((value, index) => {
                  return <MenuItem value={value}>{value}</MenuItem>;
                })}
              </Select>
            </FormControl>

我收到此错误TypeError: values.map is not a function

感谢您的帮助。

【问题讨论】:

  • 嗨,bamerf,刚刚给你写了一个解决方案,如果有帮助,请告诉我并检查沙箱 :)

标签: reactjs material-ui react-hooks


【解决方案1】:

TypeError: values.map is not a function - 这意味着你的状态不再是一个数组。您的 handleChange 函数正在将状态转换为对象。

看起来您真正需要的是有一个额外的状态来跟踪,特别是对于选定的项目。无需改变原始状态数组。

尝试添加另一个useState()

const [selected, setSelected] = useState("Bam")

然后更新您的 handleChange 函数以更新该状态:

  function handleChange(event) {
     setSelected(event.target.value)
  }

最后将Select标签value属性连接到selected state

  <FormControl className={classes.formControl}>
     <InputLabel htmlFor="agent-simple">Agent</InputLabel>
       <Select
          value={selected}
          onChange={handleChange}
          inputProps={{
           name: "agent",
            id: "age-simple"
          }}
        >
         {values.map((value, index) => {
            return <MenuItem value={value}>{value}</MenuItem>;
         })}
       </Select>
  </FormControl>

查看工作代码框:https://codesandbox.io/s/inspiring-wave-z133o

【讨论】:

    猜你喜欢
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    • 2015-02-26
    相关资源
    最近更新 更多