Decorator
配置: decorator是ES7中的提案,所以需要babel转译后才能被现代浏览器解析。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
{ "presets": ["@babel/preset-env", "@babel/preset-react"], "plugins": [ ["import", { "libraryName": "antd", "style": "css" }], ["@babel/plugin-proposal-decorators", { "legacy": true }], ["@babel/plugin-proposal-class-properties", { "loose": true }], ] }
|
Decorator语法:
1、修饰类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @fly class Person {}
function fly(target){ target.canFly = true return target }
Person.canFly const p1 = new Person() p1.canFly
|
2、修饰类的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| // App.js class App extends Component { componentDidMount() { window.addEventListener("scroll", this.scroll, false); }
@throttle scroll() { console.log("scroll"); } render(){ return <div/> } }
// util.js /* * 函数节流, */ export function throttle(target, name, descriptor) { const initialValue = descriptor.value; const interval = 1000; let timer = undefined; descriptor.value = function(...args) { if (timer) return; timer = setTimeout(() => { clearTimeout(timer); timer = undefined; }, interval); initialValue.call(this, args); // 执行原函数 }; return descriptor; }
|
https://juejin.im/post/5cbeadb95188250aa52c7b1b