【问题标题】:Material-UI Select e.target.value is undefinedMaterial-UI Select e.target.value 未定义
【发布时间】:2019-11-19 07:55:40
【问题描述】:

我在我的一个 React 项目中使用 Material-UI 的 Select 组件。我需要分组显示下拉数据,因此我使用<MenuItem> 包裹<ListSubheader>。我很难获得MenuItems 的价值。如果我的代码有任何明显错误,请告诉我。

<FormControl>
    <InputLabel>Product type</InputLabel>
    <Select
    id="product-type"
    input={<Input id="grouped-select" />}
    value={this.state.productType}
    autoWidth={true}
    style={{ width: 200 }}
    onChange={(e, child) => {
        console.log(e.target.value); // undefined!
    }}
    >
    {this.state.productList.map((p, i) => {
        const list = p[1];

        let items = list.map((e, j) => {
        return (
            <MenuItem key={j} value={e.name}>
            {e.name}
            </MenuItem>
        );
        });

        return (
        <div>
            <ListSubheader key={i}>{p[0]}</ListSubheader>
            {items}
        </div>
        );
    })}
    </Select>
</FormControl>

【问题讨论】:

  • 试试这个 onChange={handleChange} 函数是 const handleChange = event => { setAge(event.target.value); };
  • 你能 console.log this.state.productList 告诉我们价值吗?您的数据也是来自 api 吗?
  • @AtinSingh 是的,它来自 API,并且数据实际上就在那里。看起来像这样:` [ [“Garments”,[ {“pk”:2,“master_category”:{“pk”:1,“name”:“Garments”},“name”:“T恤”} ] ] ] `
  • @GauravRoy 我已经尝试创建一个handleChange 函数,但是,e.target.value 仍然未定义。
  • 是数组还是数组?

标签: reactjs material-ui


【解决方案1】:

正如其他人所提到的,e.target.value 返回 undefined 的原因是因为 MenuItem 不是 Select 的直接子代。由于productList 被动态设置到下拉列表中,因此必须以这样的方式呈现:

ListSubheader0
   Item0
   Item1
ListSubheader1
   Item2
   Item3
   Item4
   ...
...

我没有将我的 ListSubheaderMenuItem 包装在无法读取 target.valuediv 标记中,而是返回了一个数组。

return [
    <ListSubheader key={i}>
        {p[0]}
    </ListSubheader>, 
    items
];

【讨论】:

  • 在我的情况下确实如此。我有一个包装菜单项的
    ,这样我就可以使用 css 应用样式。现在我能够修复选择组件中的值,但我需要弄清楚如何修复样式!不过感谢您的回答!
【解决方案2】:

Material-ui 选择直接子项必须是MenuItem:

⚠️MenuItem元素必须是native时的直系后代 假的。

您需要相应地更改您的代码,以便 MenuItemSelect 的直接子代。比如:

<MenuItem key={i} value={p[0]}>
    <ListSubheader key={i}>{p[0]}</ListSubheader>
    {items}
</MenuItem>

它可能看起来不同,但e.target.value 现在不会未定义。

【讨论】:

  • 如果有意义的话,这将使我的副标题“可选择”。我的目标是让我的下拉菜单保持与现在相同的方式(Subheader0 -> 相关项目,Subheader1 -> 相关项目,...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-22
  • 1970-01-01
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多