手写装饰器
手写装饰器
目标:写一个防抖
utils/decorator.js
export function debounce(timeout){
/**
* 去抖
* @param {Number} timeout
*/
return function(target,key,descriptor){
// 获取被装饰的方法
const lodValue = descriptor.value;
// 初始化timer
let timer = null ;
// 覆盖被装饰的方法
descriptor.value = function(){
clearTimeout(timer);
timer = setTimeout(()=>{
oldValue.apply(this,arguments)
},timeout)
};
return descriptor;
}
}
类属性装饰器可以用在类的属性、方法、get/set 函数中,一般会接收三个参数:
- target:被修饰的类
- name:类成员的名字
- descriptor:属性描述符,对象会将这个参数传给
Object.defineProperty
装饰器的应用
import { debounce } from './utils.js';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 1,
};
this.handleClick = this.handleClick.bind(this);
}
/*
- 装饰器可以装饰类和类的方法,需要注意的是装饰方法是原型对象方法
- no fn(){}
- ok fn = () => {}
*/
@debounce(200)
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<button onClick={this.handleClick}>add-click</button>
<p>{this.state.count}</p>
</div>
)
}
}
export default App;
修改页面 (opens new window)
Last Updated: 12/20/2021, 5:53:52 AM