流星装饰员1.4

时间:2016-08-01 00:56:21

标签: meteor reactjs decorator babeljs ecmascript-next

我试图了解装饰器如何与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 {
  //...
}

1 个答案:

答案 0 :(得分:2)

您正在将componentWillMount函数分配给类FooWidget而不是其原型。将其更改为target.prototype.componentWillMount = …。此外,在这种情况下,存储先前的componentWillMount是不必要的,因为无论如何它都是undefined

这是full working example

<强> 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"]
}
相关问题