9
我一直在阅读JavaScript中的装饰器,并认为我得到的基本前提。ES7中的类装饰器
装饰器是函数,他们收到一个或几个参数,他们应该装饰,并返回结果。
但我在一个React Boiler Plate项目中过来了一个@withStyles
装饰实现,我不明白它是如何工作的。
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 {
}
这是如何工作的?