我正在尝试调用imagesLoaded函数(在脚本区域中正确导入),但是当从组件prop中调用它时,我得到一个错误,它是未定义的。
我的代码:
var MasonryContainer = React.createClass({
imagesLoadedFunc: function() { //omitting the imageloaded call here fix everything
this.imagesloaded();
this.refs[reference].getDOMNode().imagesLoaded(function() {
this.masonry.layout()
});
},
componentDidMount: function() {
if (!isBrowser) return;
this.initializeMasonry();
this.performLayout();
this.imagesLoadedFunc();
},
componentDidUpdate: function() {
if (!isBrowser) return;
this.performLayout();
this.imagesLoadedFunc(this);
},
domChildren: [],
initializeMasonry: function(force) {
if (!this.masonry || force) {
this.masonry = new Masonry(this.refs[reference].getDOMNode(), options);
this.domChildren = this.getNewDomChildren();
}
},
getNewDomChildren: function () {
var node = this.refs[reference].getDOMNode();
var children = options.itemSelector ? node.querySelectorAll(options.itemSelector) : node.children;
return Array.prototype.slice.call(children);
},
diffDomChildren: function() {
var oldChildren = this.domChildren;
var newChildren = this.getNewDomChildren();
var removed = oldChildren.filter(function(oldChild) {
return !~newChildren.indexOf(oldChild);
});
var added = newChildren.filter(function(newChild) {
return !~oldChildren.indexOf(newChild);
});
var moved = [];
if (removed.length === 0) {
moved = oldChildren.filter(function(child, index) {
return index !== newChildren.indexOf(child);
});
}
this.domChildren = newChildren;
return {
old: oldChildren,
'new': newChildren, // fix for ie8
removed: removed,
added: added,
moved: moved
};
},
performLayout: function() {
var diff = this.diffDomChildren();
if (diff.removed.length > 0) {
this.masonry.remove(diff.removed);
this.masonry.reloadItems();
}
if (diff.added.length > 0) {
this.masonry.appended(diff.added);
}
if (diff.moved.length > 0) {
this.masonry.reloadItems();
}
this.masonry.layout();
},
componentWillReceiveProps: function() {
setTimeout(function() {
this.masonry.reloadItems();
this.forceUpdate();
}.bind(this), 0);
},
render: function () {
return (
<div className="content" ref="masonryContainer">
<div className='Item'>
<img src="/img/gallery/3.jpg"></img>
</div>
<div className='Item'>
<img src="/img/gallery/11.jpg"></img>
</div>
<div className='Item'>
<img src="/img/gallery/12.jpg"></img>
</div>
<div className='Item'>
<img src="/img/gallery/12.jpg"></img>
</div>
<img src="/img/gallery/4.jpg"></img>
<img src="/img/gallery/5.jpg"></img>
<img src="/img/gallery/6.jpg"></img>
<img src="/img/gallery/7.jpg"></img>
<img src="/img/gallery/8.jpg"></img>
<img src="/img/gallery/9.jpg"></img>
</div>
);
}
});
React.render(
<MasonryContainer/>, document.getElementById('reactbody')
)
</script>
如果我在反应组件之外调用imageloaded构造函数,它就可以了。 我错过了什么?
答案 0 :(得分:1)
您使用此处加载了调用的图片,
this.imagesloaded();
但是,imagesloaded不是组件的一部分,也不是React中的标准。因此,this.images加载是未定义的,因为它从未被声明过。尝试删除&#34;此&#34;声明的一部分。
imagesLoadedFunc: function() {
imagesloaded();
//the rest of the method
},