Material UI Autocomplete如何显示名称为选项文本,提交时获取对应ID值
解法说明
你当前将onSelect事件绑定在内部的TextField组件上,TextField展示的内容就是getOptionLabel返回的option.name,因此必然只能拿到name值。Autocomplete组件本身提供了原生回调来获取完整选中项,不需要通过input的target.value间接取值,是官方推荐的实现方式。
实现代码
import { useState } from 'react'; import Autocomplete from '@mui/material/Autocomplete'; import TextField from '@mui/material/TextField'; import CircularProgress from '@mui/material/CircularProgress'; // 你的options数据,注意补全Mary的引号 const options = [ { id: "01", name: "Peter" }, { id: "02", name: "Mary" }, { id: "03", name: "John" } ] function YourComponent() { const [open, setOpen] = useState(false); const [loading, setLoading] = useState(false); // 新增状态存储选中的id const [selectedId, setSelectedId] = useState(null); return ( <Autocomplete id="asynchronous-demo" fullWidth open={open} onOpen={() => setOpen(true)} onClose={() => setOpen(false)} getOptionLabel={(option) => option.name} options={options} loading={loading} {/* 新增配置:匹配选中值和选项 */} value={options.find(option => option.id === selectedId) || null} isOptionEqualToValue={(option, value) => option.id === value.id} {/* 新增选中回调,直接拿id */} onChange={(event, newValue) => { if (newValue) { const targetId = newValue.id; setSelectedId(targetId); // 替换你原来的onSelectHandle逻辑,直接传入id即可 onSelectHandle({ target: { value: targetId } }); } }} renderInput={(params) => ( <TextField {...params} label="Asynchronous" variant="outlined" onChange={(event) => { // 原逻辑有BUG:|| 改为 &&,否则判断永远为真 if (event.target.value !== '' && event.target.value !== null) { onChangeHandle(event.target.value) } }} InputProps={{ ...params.InputProps, endAdornment: ( <React.Fragment> {loading ? <CircularProgress color="inherit" size={20} /> : null} {params.InputProps.endAdornment} </React.Fragment> ), }} /> )} /> ) }
可选方案(如需保持event.target.value取值逻辑)
如果不想修改原有的onSelectHandle入参格式,上述代码中已经在onChange里构造了符合要求的event对象传入,无需修改原有业务逻辑。
内容的提问来源于stack exchange,提问作者Manzana
相关产品推荐
相关产品推荐

