【问题标题】:Decorators in Meteor 1.4Meteor 1.4 中的装饰器
【发布时间】:2016-12-05 23:49:56
【问题描述】:

我正在尝试了解装饰器如何与 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 () {
     // ...
  };
}

【问题讨论】:

  • 装饰器是一个提议,它们不是 ES7 的一部分。
  • 很公平。谢谢。

标签: meteor reactjs decorator babeljs ecmascript-next


【解决方案1】:

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

这是full working example

ma​​in.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');
  };
};

ma​​in.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 1.4 测试)。也许代码的其他部分有问题?
  • 我没有看到代码有任何问题(即控制台中没有错误),因为布局正常呈现,无论是否装饰。我还尝试了一种替代方法,使用包装器来扩展FooWidget 类(即class FooWidget extends TestDecorator(Component))并且替代方法有效!所以,我不知道为什么装饰器不起作用。 ://
  • 我使用上面的示例创建了一个 repo,它在 Meteor 1.4 中绝对有效:github.com/klaussner/decorator-example(它在控制台中输出Decorating…,然后是Component will mount)。也许这可以帮助您隔离问题。 :)
  • 这是答案和一个很好的例子,对我很有帮助。我遇到的一个问题是 Babeljs.io 上的示例 Simple class decorator 装饰了我的构造函数而不是类。上面的答案在这里按预期工作。
猜你喜欢
  • 2017-01-08
  • 2013-01-10
  • 1970-01-01
  • 2013-10-24
  • 1970-01-01
  • 2017-10-12
  • 1970-01-01
  • 2011-09-03
  • 2015-11-18
相关资源
最近更新 更多