我试图了解装饰器如何与 Meteor 1.4 一起工作。据我read ,支持此功能。
现在,我不确定如何实际实现它。来自 this blog ,要装饰一个类,我需要这段代码
export const TestDecorator = (target) => {
let _componentWillMount = target.componentWillMount;
target.componentWillMount = function () {
console.log("*** COMPONENT WILL MOUNT");
_componentWillMount.call(this, ...arguments);
}
return target;
}
然后将其用作
import React, { Component } from 'react';
import { TestDecorator } from 'path/to/decorator.js';
@TestDecorator
export default class FooWidget extends Component {
//...
}
代码可以编译,但在渲染组件时没有任何输出。
我错过了什么?如何在 Meteor 中实现装饰器?这是正确的解决方案吗?有什么替代方案吗?
编辑
我已经尝试过了,还是不行
export const TestDecorator = (target) => {
console.log("*** THIS IS NOT EVEN DISPLAYED! ***");
target.prototype.componentWillMount = function () {
// ...
};
}
最佳答案
您正在将 componentWillMount
函数分配给类 FooWidget
而不是它的原型(prototype)。将其更改为 target.prototype.componentWillMount = ...
。此外,在这种情况下,存储之前的 componentWillMount
是不必要的,因为它无论如何都是 undefined
。
这是一个full working example :
main.html
<head>
<title>decorators</title>
</head>
<body>
<div id="root"></div>
</body>
装饰器.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"]
}
关于meteor - Meteor 1.4 中的装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38689684/