我一直在阅读 JavaScript 中的装饰器,并认为我已经掌握了基本前提。
装饰器是函数,它们作为一个或多个参数接收它们应该装饰的内容,并返回结果。
但是我@withStyles
在一个 React Boiler Plate 项目中遇到了一个装饰性的实现,我不明白它是如何工作的。
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 {
}
这是如何运作的?