peyton Blog
查看源码 (opens new window)
查看源码 (opens new window)
  • BLOG
2021-12-17

手写装饰器

手写装饰器

目标:写一个防抖

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 函数中,一般会接收三个参数:

  1. target:被修饰的类
  2. name:类成员的名字
  3. 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
最近更新
01
02
03
css垂直居中
12-17
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式