React中如何结合Typeahead实现带自动补全的表单搜索提交功能?
问题根因
你当前的提交逻辑依赖Keyword状态变量,但仅用Typeahead组件时,用户输入和选中的内容只会更新singleSelections,没有同步到Keyword,导致提交时判断关键词为空,功能失效。无需同时保留FormControl和Typeahead两个输入组件,Typeahead本身就包含输入框能力,只需同步状态即可。
修复代码
组件部分修改
<Form className="main_form" onSubmit={submitHandler} inline style={{ marginRight: 100 }} > <Typeahead id="basic-typeahead-single" labelKey="name" onChange={(selected) => { setSingleSelections(selected); // 同步选中的自动补全项到搜索关键词 setKeyword(selected.length ? selected[0].name : ''); }} // 同步用户手动输入的内容到搜索关键词 onInputChange={(inputValue) => setKeyword(inputValue)} options={products} placeholder="Search for products" selected={singleSelections} /> <Button type="submit" variant="outline-primary" className="main-btn"> <i className="fas fa-search" style={{ fontSize: 13 }}></i> </Button> </Form>
提交逻辑修改
const submitHandler = (e) => { e.preventDefault(); const trimmedKeyword = Keyword.trim(); if (trimmedKeyword) { // 对关键词做编码,避免特殊字符导致路由异常 history.push(`/?keyword=${encodeURIComponent(trimmedKeyword)}`); // 可选:提交后清空输入和选中状态 setSingleSelections([]); setKeyword(''); } else { history.push(history.location.pathname); } };
修改说明
- 给Typeahead新增
onInputChange属性,监听用户手动输入的内容,实时同步到搜索关键词状态Keyword - 修改Typeahead的
onChange回调,选中自动补全选项时同步选中内容到Keyword - 修复原提交逻辑中重复调用
history.push的错误,新增关键词编码和空格校验逻辑,避免异常
内容的提问来源于stack exchange,提问作者Sohanur Rahman Shanto 16209570
相关产品推荐
相关产品推荐

