import React, { Component } from 'react';
class Debounce extends Component{
constructor(props) {
super(props);
}
inputValue = (content) => {
console.log(content);
}
debounce = (fun, wait) => {
return (...rest) => {
let args = rest;
console.log(this.timerId);
if(this.timerId) clearTimeout(this.timerId);
this.timerId = setTimeout(() => {
fun(args);
}, wait);
}
}
throttle = (fun, wait=3000) => {
return (...rest) => {
let args = rest;
if(!this.canRun){
this.canRun = setTimeout(() => {
fun(args);
this.canRun = null;
}, wait);
}
}
}
onUndebounceClick = (e) => {
console.log(e.target.value);
}
onDebounceClick = (e) => {
let debounceKeyup = this.debounce(this.inputValue, 3000);
debounceKeyup(e.target.value);
}
onThrottleClick = () => {
let throttleKeyup = this.throttle(this.inputValue, 3000);
throttleKeyup('a');
}
render() {
return(
<div>
正常的input: <input onKeyUp={this.onUndebounceClick}/><br/>
防抖的input: <input onKeyUp={this.onDebounceClick}/><br/>
节流的button: <button onClick={this.onThrottleClick}>click</button>
</div>
)
}
}
export default Debounce;
在React中实现防抖节流
最新推荐文章于 2024-07-25 17:14:51 发布
本文介绍了一个React组件Debounce的实现,该组件展示了如何使用防抖(debounce)和节流(throttle)技术。在输入框的onKeyUp事件中,分别应用了防抖和节流函数,以限制事件处理函数的执行频率,提高性能。防抖用于在用户停止输入一段时间后才执行,而节流则确保在固定时间间隔内执行一次。
摘要由CSDN通过智能技术生成