首页 > 解决方案 > 使用时我不能同时使用 onSearch 和 onInputChange

问题描述

所以正如我在标题中所说,我不能同时使用 onSearch 和 onInputChange。如果我尝试,onSearch 会被忽略。你能告诉我为什么或者有替代 onInputChange 的方法吗?我在表单中使用 AsyncTypeahead,因此单击按钮时需要这些值。

const [from, setFrom] = useState('');
const onSearchStart = (query) => {
  setTypeAhead({
    ...typeAhead,
    startIsLoading: true
   })
   setFrom(query)
   getStations(query).then(r => {
   setTypeAhead({
     ...typeAhead,
     startIsLoading: false,
     startOptions: r || []
   })
 })
}

return(
  <AsyncTypeahead
    id={"from"}
    isLoading={typeAhead.startIsLoading}
    options={typeAhead.startOptions}
    onInputChange={setFrom}
    onSearch={onSearchStart}
  />  
)

这不是全部代码,但它显示了导致错误的所有内容

标签: react-bootstrap-typeahead

解决方案


作为一种解决方法,您可以使用它useRef来不触发重新渲染。这是代码:

const fromRef = useRef('');
const onSearchStart = (query) => {
  ...
}

return(
  <AsyncTypeahead
    ...
    onInputChange={(text) => {
      fromRef.current = text;
    }}
    onSearch={onSearchStart}
  />  
)

推荐阅读