小编典典

仅当用户停止输入时才如何开始搜索?

reactjs

用户停止键入时需要执行搜索。我知道我应该使用 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方法。


阅读 240

收藏
2020-07-22

共1个答案

小编典典

您可以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在构造函数中绑定处理程序函数。

constructor(props) {
   super(props);
   this.changeName = this.changeName.bind(this);
}
2020-07-22