ES7-Decorator
デコレータの一般的な使用法
react-redux
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { increment, decrement } from '../redux/actions'
@connect(
state=>({value: state.test}),
{increment,decrement}
)
class Counter extends Component {
onIncrease() {
this.props.increment(5);
}
onDecrement() {
this.props.decrement(3);
}
render() {
const { value } = this.props;
return (
<div>
Test: {value}
<button onClick={this.onIncrease.bind(this)}> </button>
<button onClick={this.onDecrement.bind(this)}> </button>
</div>
);
}
}
export default Counter;
Ant Design
import React, { Component } from 'react';
import { Form } from 'antd';
@Form.create({
name: 'ingestion_form'
})
class IngestionForm extends Component {
// フォームコンポーネント
}
ES7-Decoratro
"携帯電話にケースを追加するようなもので、通話や充電といった携帯電話本来の機能には影響しません;
"
デコレーターは、「カッター指向プログラミング」を実装する方法です。
具体的には何をするのでしょうか?クラスやメソッド、アクセサ、プロパティ、パラメータを "デコレート" します。 "デコレート" とは、クラス・デコレータ、メソッド・デコレータ、 アクセサ・デコレータ、プロパティ・デコレータ、パラメータ・デコレータのことです。
クラスのデコレータ
@testable
class MyTestableClass {
// ...
}
function testable(target) {
target.isTestable = true;
}
MyTestableClass.isTestable // true
// これは
class MyTestableClass {
static isTestable = true
}
基本的に、デコレーターの振る舞いは次のようになります。
@decorator
class A {}
//
class A {}
A = decorator(A) || A;
パラメータを拡張するには、デコレータの外側に関数のレイヤーを追加します。
function testable(isTestable) {
return function(target) {
target.isTestable = isTestable;
}
}
@testable(true)
class MyTestableClass {}
MyTestableClass.isTestable // true
@testable(false)
class MyClass {}
MyClass.isTestable // false
target.prototype.valueインスタンス・プロパティを追加したい場合は、.
/属性デコレータ
ES6のクラスを見る
class Cat {
say() {
console.log("meow ~");
}
}
Object.defineProperty実際にクラス属性を追加する場合は、3つのパラメータ(target、name、descriptor)を受け付けるメソッドを使用します。
function Cat() {}
Object.defineProperty(Cat.prototype, "say", {
value: function() { console.log("meow ~"); },
enumerable: false,
configurable: true,
writable: true
});
Object.defineProperty"プロパティ/メソッド・デコレーターのパラメーターは、上記で使用したものと同じです。"
たとえば、属性の一部を読み取り専用にして他の人が変更できないようにしたい場合があります:
function readonly(target, name, descriptor) {
discriptor.writable = false;
return discriptor;
}
class Cat {
@readonly
say() {
console.log("meow ~");
}
}
var kitty = new Cat();
kitty.say = function() {
console.log("woof !");
}
kitty.say() // meow ~
class Math {
@log
add(a, b) {
return a + b;
}
}
function log(target, name, descriptor) {
var oldValue = descriptor.value;
descriptor.value = function() {
console.log(`Calling ${name} with`, arguments);
return oldValue.apply(this, arguments);
};
return descriptor;
}
const math = new Math();
// passed parameters should get logged now
math.add(2, 4);
デコレーターのJS記述
A decorator is:
- an expression
- that evaluates to a function
- that takes the target, name, and decorator descriptor as arguments
- and optionally returns a decorator descriptor to install on the target object
babel --plugins transform-decorators-legacy es6.js > es5.js





