在react中创建防抖方法

在react中input事件防抖方法

import React, { Component } from 'react';

//防抖方法
function debounce(fn, ms = 500) {
    let timeoutId
    return function () {
      clearTimeout(timeoutId)
      timeoutId = setTimeout(() => {
        fn.apply(this, arguments)
      }, ms)
    }
  }
  
export default class input extends Component {
    constructor(props) {
        super(props);
        this.state = {
            inputValue:''
        };

        this.isPhoneLegal = debounce(this.isPhoneLegal, 1000);//调用设定好的防抖方法
    };

    handleKeyUp = (e) => {
        this.isPhoneLegal(e.target.value) // 对用户输入进行判断
        this.setState({
            inputValue : e.target.value
        },()=>{
            console.log('tag', this.state.inputValue) // 实时获取
        })
    }
    isPhoneLegal  = (phone) => {
        console.log(phone)  // 防抖后获取的值
    } 
    
    render() {
        return (
            <div>
               <input  value={this.state.inputValue}  onChange={ this.handleKeyUp} placeholder="请输入手机号"/>
            </div>
        )
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。