我试图将 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/