我试图了解装饰器如何与Meteor 1.4配合使用。从我read开始,支持此功能。
现在,我不确定如何实际实现它。从this blog开始,为了装饰一个类,我需要这个代码
api/{controller}/{id}
然后将其用作
export const TestDecorator = (target) => {
let _componentWillMount = target.componentWillMount;
target.componentWillMount = function () {
console.log("*** COMPONENT WILL MOUNT");
_componentWillMount.call(this, ...arguments);
}
return target;
}
代码编译,但在渲染组件时不会输出任何内容。
我错过了什么?如何在Meteor中实现装饰器?这是正确的解决方案吗?有什么替代方案?
我试过这个,但它仍然不起作用
import React, { Component } from 'react';
import { TestDecorator } from 'path/to/decorator.js';
@TestDecorator
export default class FooWidget extends Component {
//...
}
答案 0 :(得分:2)
您正在将componentWillMount
函数分配给类FooWidget
而不是其原型。将其更改为target.prototype.componentWillMount = …
。此外,在这种情况下,存储先前的componentWillMount
是不必要的,因为无论如何它都是undefined
。
<强> main.html中强>
<head>
<title>decorators</title>
</head>
<body>
<div id="root"></div>
</body>
<强> decorator.js 强>
export const TestDecorator = (target) => {
console.log('Decorating…');
target.prototype.componentWillMount = function() {
console.log('Component will mount');
};
};
<强> main.jsx 强>
import React, { Component } from 'react';
import { render } from 'react-dom';
import { TestDecorator } from '/imports/decorator.js';
import './main.html';
@TestDecorator
class FooWidget extends Component {
render() {
return <h1>FooWidget</h1>;
}
}
Meteor.startup(function() {
render(<FooWidget/>, document.getElementById('root'));
});
<强> .babelrc 强>
{
"plugins": ["transform-decorators-legacy"]
}