我在 React native 中有一个使用文本输入的搜索功能,但搜索需要调用 API,所以我想在用户完成输入 2 秒后让 onChangeText
运行,
我尝试过使用 setInterval
或 setTimeout
但这些都不起作用,
这是我试过的代码:
<TextInput
placeholder="search"
onChangeText={(text) => {
setTimeout(() => {
console.log(text)
console.log("Kepanggil TimeOUTNYAA")
params.onSearchText(text)
}, 2000);
}
}
//function onSearchText
onSearchText(searchText){
this.setState({text:searchText},()=>{
this._loadMore() // here's a function to call the API
})
}
实际行为:
当我在 TextInput
中输入 am
时,日志显示:
预期行为:
我希望日志显示我仅 am
not a
和am
有可能吗?
最佳答案
你应该在设置新的之前清除旧的超时
<TextInput
placeholder="search"
onChangeText={(text) => {
if(this.searchWaiting)
clearTimeout(this.searchWaiting);
this.searchWaiting = setTimeout(() => {
this.searchWaiting = null;
console.log(text);
console.log("Kepanggil TimeOUTNYAA")
params.onSearchText(text)
}, 2000);
}}
/>
关于javascript - React Native - 如何处理 TextInput onChangeText 事件以在执行函数之前等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51131228/