ES7中的类装饰器 [英] Class decorators in ES7

查看:93
本文介绍了ES7中的类装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读JavaScript中的装饰器,并认为我已经掌握了基本前提。

I've been reading up on decorators in JavaScript, and think I'm getting the basic premise.

装饰器是函数,它们以a或多个参数的形式接收他们应该装饰什么并返回结果。

Decorators are functions, they receive as a or several parameters what they should decorate, and return the result.

但是我在React中遇到了一个 @withStyles 装饰的实现

But I came over a @withStyles decorated implementation in a React Boiler Plate project which I do not understand how works.

import React, { Component, PropTypes } from 'react';

function withStyles(...styles) {
  return (BaseComponent) => class StyledComponent extends Component {
    static contextTypes = {
      insertCss: PropTypes.func.isRequired,
    };

    componentWillMount() {
      this.removeCss = this.context.insertCss.apply(undefined, styles);
    }

    componentWillUnmount() {
      this.removeCss();
    }

    render() {
      return <BaseComponent {...this.props} />;
    }
  };
}

export default withStyles;

用例为

import s from './MyComponentStyle.scss';

@withStyles(s)
class MyComponent extends Component {

}

这是如何工作的?

推荐答案

类装饰器可以用作工厂函数。例如:

Class decorators can be used as factory functions. For Example:

function myDecorator(value) {
   return function(target) {
      target.myProperty = value;
   }
}

@myDecorator('myValue')
class MyClass { }

在您的示例中,工厂函数返回包装原始类的构造函数。此函数用于创建对象而不是原始类。在您的情况下,它处理事件( componentWillMount componentWillUnmount )以便插入/删除css并使用

In your example the factory function returns constructor function which wraps original class. This function is used to create object instead of the original class. In your case it handles events (componentWillMount, componentWillUnmount) in order to insert/remove css and renders the original component with it's props.

这是一个非常简单的示例,演示了装饰器如何覆盖原始构造函数:

This is very simple example demonstrating how is the original constructor function overrided by decorator:

function myDecorator(name) {
   return (target) => class Wrapper {
       sayHello() {
           const targetObject = new target();
           console.log(`wrapper ${name} says hello`);
           targetObject.sayHello();
       }
       wrapperMethod() {
           console.log('calling wrapper function');
       }
   };
}

@myDecorator('Jack')
class MyClass {
    sayHello() {
        console.log('original says hello');
    }
    myMethod() {
       console.log('calling original function');
    }
}

var obj = new MyClass();

obj.sayHello();
//wrapper Jack says hello
//original says hello

obj.wrapperMethod();
//calling wrapper function

obj.myMethod();
//TypeError: obj.myMethod is not a function

这篇关于ES7中的类装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆