javascript - 将 React mixin 导出到单独的文件中

标签 javascript reactjs mixins reactjs-flux

我试图将 SetIntervalMixin 分离到与组件类文件不同的文件中。也许我不完全理解 module.export 是如何工作的但是......如果我这样做:

module.exports = {
 componentWillMount: function() {
   this.intervals = [];
 },
 setInterval: function() {
   this.intervals.push(setInterval.apply(null, arguments));
 },
 componentWillUnmount: function() {
   this.intervals.map(clearInterval);
 }
};

在 SetIntervalMixin.js 中,然后从组件中使用它可以正常工作:

var SetIntervalMixin = require('../util/mixins/SetIntervalMixin')

但是如果我这样写:

var SetIntervalMixin = {

  componentWillMount: function() {
    this.intervals = [];
  },
  setInterval: function() {
    this.intervals.push(setInterval.apply(null, arguments));
  },
  componentWillUnmount: function() {
    this.intervals.map(clearInterval);
  }
};

module.export = SetIntervalMixin;

它不起作用(尝试调用 setInterval() 时未定义)。我认为之后缺少了一些东西:

SetIntervalMixin = ...

就像定义组件一样,您使用:

var yourComponent = React.createClass(...

是否有类似的东西,如 React.createMixin(.. ?或者如何是最好的方法来做到这一点。

谢谢。

最佳答案

你的代码是正确的,只是第二个版本中有一个拼写错误(应该是module.exports而不是module.export):

var SetIntervalMixin = {

  componentWillMount: function() {
    this.intervals = [];
  },
  setInterval: function() {
    this.intervals.push(setInterval.apply(null, arguments));
  },
  componentWillUnmount: function() {
    this.intervals.map(clearInterval);
  }
};

module.exports = SetIntervalMixin;

关于javascript - 将 React mixin 导出到单独的文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25487160/

相关文章:

javascript - 使用 Labjs 我得到一个 "$ is not defined"错误但是 js 仍然有效,不知道为什么 :(

reactjs - 我一直在尝试使用 npx create-react-app 创建一个新的 React 项目,但出现错误

ReactJS - Redux Form - 如何根据单选字段元素有条件地显示/隐藏元素?

ocaml - 如何在 OCaml 中实现 mixin

javascript - 禁用左键单击(用于心理实验),但在 IE 中焦点发生变化。如何预防?

javascript - 如何通过按钮切换表单?

javascript - 单击后将外部数据加载到 div n 秒 - 一次

ruby-on-rails - 使用 React.js 作为前端时如何处理 Rails 中的数据绑定(bind)?

C++ 动态类型构造和检测

当 mixin 保存在单独的文件夹中时,Sass 编译器会抛出 'undefined mixin' 错误