使用AsyncTypeahead时同时绑定onSearch与onInputChange导致onSearch失效
问题原因
这是react-bootstrap-typeahead库中AsyncTypeahead组件的原生设计逻辑:当你传入自定义onInputChange回调时,组件会覆盖内部默认的输入变更处理流程,而默认流程本身负责触发onSearch事件,因此自定义onInputChange后onSearch默认不会被触发。
解决方案
方案1:合并逻辑到onInputChange(优先推荐)
直接把原本写在onSearch里的搜索逻辑放到onInputChange回调中执行即可,无需单独绑定onSearch,同时可以保留输入值的状态同步,适配表单提交场景:
const [from, setFrom] = useState(''); const handleInputChange = (query) => { setFrom(query); // 直接执行原有搜索逻辑,用函数式更新避免闭包问题 setTypeAhead(prev => ({ ...prev, startIsLoading: true })); getStations(query).then(r => { setTypeAhead(prev => ({ ...prev, startIsLoading: false, startOptions: r || [] })); }); }; return( <AsyncTypeahead id="from" isLoading={typeAhead.startIsLoading} options={typeAhead.startOptions} onInputChange={handleInputChange} value={from} // 绑定value转为受控组件,避免输入状态不同步 /> )
如果需要和原生onSearch一样的防抖效果,给handleInputChange加一层防抖封装即可。
方案2:保留双事件绑定
如果确实需要同时保留两个回调,只需要在onInputChange回调末尾返回true,即可让组件继续执行默认的onSearch触发逻辑:
const handleInputChange = (query) => { setFrom(query); // 返回true告知组件继续执行默认的搜索触发逻辑 return true; }; return( <AsyncTypeahead id="from" isLoading={typeAhead.startIsLoading} options={typeAhead.startOptions} onInputChange={handleInputChange} onSearch={onSearchStart} /> )
表单提交取值补充方案
如果不想单独维护输入值的状态,也可以通过ref直接读取组件的当前输入值:
const typeaheadRef = useRef(null); const handleSubmit = () => { const currentInputValue = typeaheadRef.current?.input.value; // 执行后续提交逻辑 } return ( <> <AsyncTypeahead ref={typeaheadRef} id="from" isLoading={typeAhead.startIsLoading} options={typeAhead.startOptions} onSearch={onSearchStart} /> <button onClick={handleSubmit}>提交</button> </> )
内容的提问来源于stack exchange,提问作者CORRIT_
相关产品推荐
相关产品推荐

