meteor - Meteor 1.4 中的装饰器

标签 meteor reactjs decorator babeljs ecmascript-next

我试图了解装饰器如何与 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 :

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

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 - Meteor 1.4 中的装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38689684/

相关文章:

decorator - ReBus:无法将 sagas 与处理程序装饰器一起使用

javascript - Webpack babel 6 ES6 装饰器

meteor - 在 Meteor 中创建用户时获取客户端的 IP

function - 使用 Meteor 从单独的文件中调用函数

javascript - React Native - 通过 onPress 传递字符串或变量

javascript - 使用 Reactstrap 从 API 填充下拉列表

python - 我可以在调用函数之前延迟装饰器的发生吗?

javascript - 如何使用 React 从客户端的 Meteor 集合中检索数据?

android - Meteor 应用程序,如果我们添加一个新的 cordova 插件,我们是否必须重新提交该应用程序或由 meter hotcode push 处理?

javascript - 执行连接时来自 firebase 的数据排序不正确