用户停止键入时需要执行搜索。我知道我应该使用 setTimeout() 。但是使用 Reactjs我找不到它是如何工作的。 有人可以告诉我当用户停止键入几秒钟(假设为5)时如何调用方法(将处理Search)。我不知道该在哪里编写代码来检查用户是否停止键入。
import React, {Component, PropTypes} from 'react'; export default class SearchBox extends Component { state={ name:" ", } changeName = (event) => { this.setState({name: event.target.value}); } sendToParent = () => { this.props.searching(this.state.name); } render() { return ( <div> <input type="text" placeholder='Enter name you wish to Search.' onChange={this.changeName} /> </div> ); } }
我想在用户停止键入时调用sendToParent方法。
您可以setTimeout按照以下方式使用您的代码,
setTimeout
state = { name: '', typing: false, typingTimeout: 0 } changeName = (event) => { const self = this; if (self.state.typingTimeout) { clearTimeout(self.state.typingTimeout); } self.setState({ name: event.target.value, typing: false, typingTimeout: setTimeout(function () { self.sendToParent(self.state.name); }, 5000) }); }
另外,您需要changeName在构造函数中绑定处理程序函数。
changeName
constructor(props) { super(props); this.changeName = this.changeName.bind(this); }