如何仅在用户停止输入时开始搜索? [英] How to start search only when user stops typing?

查看:37
本文介绍了如何仅在用户停止输入时开始搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在用户停止输入时执行搜索.我知道我应该使用 setTimeout() .但是使用 Reactjs 我无法找到它是如何工作的. 有人可以告诉我如何在用户停止输入几秒钟(假设 5)时调用方法(将处理搜索).我想不通找出在哪里编写代码以检查用户是否已停止输入.

import React, {Component, PropTypes} from 'react';导出默认类 SearchBox 扩展组件 {状态={名称:" ",}更改名称 = (事件) =>{this.setState({name: event.target.value});}sendToParent = () =>{this.props.searching(this.state.name);}使成为() {返回 (<div><input type="text" placeholder='输入您要搜索的名称.'onChange={this.changeName}/>

);}}

我想在用户停止输入时调用 sendToParent 方法.

解决方案

你可以对你的代码使用 setTimeout 如下,

state = {名称: '',打字:假,打字超时:0}更改名称 = (事件) =>{const self = this;如果(self.state.typingTimeout){clearTimeout(self.state.typingTimeout);}self.setState({名称:event.target.value,打字:假,打字超时:setTimeout(函数(){self.sendToParent(self.state.name);}, 5000)});}

另外,你需要在构造函数中绑定changeName处理函数.

构造函数(道具){超级(道具);this.changeName = this.changeName.bind(this);}

I need to perform a Search when user stops typing.I know I am supposed to use setTimeout() . But with Reactjs I cant find how it works. Can someone please tell me how to invoke a method (that will handle Search) when the user stops typing for a few seconds (suppose 5).I cant figure out where to write the code to check that the user has stopped typing.

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>
        );
    }
}   

I want to invoke the sendToParent method when the user stops typing.

解决方案

You can use setTimeout with respect to your code as follows,

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)
    });
}

Also, you need to bind changeName handler function in constructor.

constructor(props) {
   super(props);
   this.changeName = this.changeName.bind(this);
}

这篇关于如何仅在用户停止输入时开始搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆