美文网首页
在react中创建防抖方法

在react中创建防抖方法

作者: 考拉_2044 | 来源:发表于2019-08-01 12:19 被阅读0次

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

相关文章

网友评论

      本文标题:在react中创建防抖方法

      本文链接:https://www.haomeiwen.com/subject/mrjqdctx.html