0

我试图将 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(.. 的东西?或者最好的方法是如何做到这一点。

谢谢。

4

1 回答 1

4

您的代码是正确的,您只是在第二个版本中有一个错字(应该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;
于 2014-08-25T14:26:41.657 回答