如何获取Material UI Autocomplete选中值及getOptionLabel报错兼容咨询
结论
你提供的代码无法在material-ui ^4.12.3版本中正常运行,存在多处不符合v4 API规范和组件使用逻辑的问题,具体分析和修复方案如下:
报错原因分析
MUI: The
getOptionLabelmethod of Autocomplete returned number (0) instead of a string for 0.
这个报错的直接诱因是Autocomplete组件的value值和options项的结构不匹配:
- 你的
Items数组里所有选项都是{label: 字符串}格式的对象 - 但你给
useState设置的初始值是数字0,和选项结构完全不一致
MUI默认的getOptionLabel会尝试读取传入value的label属性作为展示文本,数字类型没有label属性,最终返回了数字0,不符合要求的字符串类型,因此抛出报错。
其他不兼容/错误点
- Autocomplete的
onChange回调使用错误:v4版本的Autocomplete的onChange第二个参数才是当前选中的完整option对象,你直接读取e.target.value无法拿到正确的选中值 sx属性是MUI v5新增的特性,在v4版本中完全不支持,会直接失效
修复后可在v4.12.3运行的代码
import React, { useState } from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from "@mui/material/Autocomplete"; export default function ComboBox() { // 初始值设为null,和后续选中的对象类型匹配 const [selected, setSelected] = useState(null); // 取第二个参数作为选中值 const handleChange = (e, newValue) => setSelected(newValue); // 打印选中的label值 console.log(selected?.label); return ( <Autocomplete disablePortal id="combo-box-demo" options={Items} // 替换sx为v4支持的style属性 style={{ width: 300 }} value={selected} onChange={handleChange} // 显式声明getOptionLabel,避免默认行为异常 getOptionLabel={(option) => option.label} renderInput={(params) => <TextField {...params} label="Items" />} /> ); } const Items = [ { label: "Car" }, { label: "Book" }, { label: "Chair" }, { label: "Pencil" } ];
内容的提问来源于stack exchange,提问作者JS3
相关产品推荐
相关产品推荐

