【问题标题】:Export React mixin in a separated file在单独的文件中导出 React mixin
【发布时间】:2014-10-18 16:15:24
【问题描述】:

我试图将 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(.. 的东西?或者最好的方法是什么。

谢谢。

【问题讨论】:

    标签: javascript reactjs mixins reactjs-flux


    【解决方案1】:

    你的代码是对的,你只是在第二个版本中有一个错字(应该是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;
    

    【讨论】:

    • 哇!你说得对。妈的,大错特错!我不喜欢使用 IntelliJ...我想在 RedHat 中安装 Atom(使用很棒的 react sn-ps - 突出显示插件),但到目前为止我还没有走运。无论如何,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-09-16
    • 2021-12-21
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 2020-07-28
    相关资源
    最近更新 更多