如何在React Material UI Autocomplete组件中禁用ENTER键清空输入的行为
解决方案
你遇到的问题根源是Material UI Autocomplete组件内部优先处理了回车键事件,且freeSolo模式下按下回车时如果没有匹配到可选中的选项,会触发内部输入状态重置,加上你没有受控管理输入值,才会出现输入框被清空的情况。你之前的拦截方法没有命中组件的内部事件逻辑,所以不生效。
按照以下步骤修改即可解决:
- 新增state受控管理输入框的值,避免组件内部私自修改状态
- 利用
onInputChange的第三个参数reason过滤掉回车触发的重置操作 - 补充回车键拦截逻辑,阻止默认行为
完整修改代码示例
import { useState, useCallback } from 'react'; import { Autocomplete, TextField } from '@mui/material'; // 你的组件内部逻辑 const SearchComponent = () => { // 新增受控输入值状态 const [inputValue, setInputValue] = useState(''); // 你的其他逻辑,比如options、debounceFetchData、classes等 const onInputChange = useCallback( (_event: React.ChangeEvent<{}>, newInputValue: string, reason: string) => { // 过滤回车触发的重置操作,仅在正常输入、选择选项时更新值 if (reason !== 'reset') { setInputValue(newInputValue); debounceFetchData(newInputValue); } }, [debounceFetchData] ); return ( <section className={classes.container}> <SearchIcon className={classes.icon} /> <Autocomplete id="search" options={options} disableClearable getOptionLabel={() => ''} filterOptions={(x) => x} fullWidth freeSolo // 绑定受控输入值 inputValue={inputValue} onInputChange={onInputChange} // 拦截回车键,阻止默认提交、选中逻辑 onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); // 如果按回车需要执行搜索等自定义逻辑,写在这里 } }} renderInput={(params) => ( <TextField {...params} placeholder="Search" variant="outlined" size="small" inputProps={{ ...params.inputProps, 'aria-label': 'Search', }} /> )} {/* 你的其他Autocomplete配置 */} /> </section> ); };
额外说明
如果你的场景下不需要保留按下回车选中高亮选项的逻辑,上面的代码可以直接使用。如果需要保留选中逻辑,只需要去掉onKeyDown里的拦截,仅保留受控inputValue和reason过滤的逻辑即可,选中后输入值会自动更新为选中项的内容,不会被清空。
内容的提问来源于stack exchange,提问作者Kim Gentes
相关产品推荐
相关产品推荐

