Material UI Autocomplete下拉框内输入框聚焦异常问题求助
问题描述
基于Material UI的Autocomplete组件开发搜索UI,在renderInput属性中嵌套了TextField作为搜索输入框,同时尝试利用noOptionsText在Autocomplete的选项区域渲染包含多个TextField的表单。当前问题:聚焦标题输入框输入内容时,输入的内容会显示在顶部的搜索输入框中,而非当前聚焦的标题输入框内。
相关代码
<Autocomplete options={[]} value={searchedName} renderInput={params => ( <TextField {...params} onChange={event => onChange(event.target.value)} onKeyDown={handleSearch} name="search" onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} /> )} noOptionsText=openSearchDropDown()} /> const openSearchDropDown= () => ( <form noValidate autoComplete="off"> <div> <label htmlFor="title:">Title:</label> <div> <TextField onChange={handleTitle} fullWidth variant="standard" /> </div> <div> <label htmlFor="Summary:">Summary:</label> <div> <TextField onChange={handleSummary} fullWidth variant="standard" /> </div> </form> )
问题截图

解决方案
这个问题的核心是Autocomplete组件会默认接管其内部所有输入框的键盘事件,将输入内容同步到自身绑定的搜索输入框中。以下是具体解决步骤:
阻止选项内输入框的事件冒泡
给标题、Summary对应的TextField添加onKeyDown事件,阻止事件向上传递到Autocomplete组件,避免其拦截输入内容:<TextField onChange={handleTitle} fullWidth variant="standard" onKeyDown={(e) => e.stopPropagation()} />对Summary的TextField执行同样操作。
修正自定义无选项区域的渲染方式
原代码中noOptionsText用法错误,该属性仅支持字符串值。若要自定义渲染内容,需使用renderNoOptions属性(Material UI v5及以上版本):<Autocomplete options={[]} value={searchedName} renderInput={params => ( <TextField {...params} onChange={event => onChange(event.target.value)} onKeyDown={handleSearch} name="search" onFocus={() => setFocus(true)} onBlur={() => setFocus(false)} /> )} renderNoOptions={() => openSearchDropDown()} />避免焦点事件被拦截
若需要确保选项内的输入框能正常获取焦点,可额外添加onFocus事件阻止冒泡:<TextField onChange={handleTitle} fullWidth variant="standard" onKeyDown={(e) => e.stopPropagation()} onFocus={(e) => e.stopPropagation()} />
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

