我正试图调用imagesLoaded函数(它在脚本区域中正确导入),但当从组件道具内部调用它时,我得到一个错误,即它是不可定义的。
我的代码:
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>
如果我在react组件之外调用映像加载的构造函数,它就可以工作了。我错过了什么?
您的呼叫图像是使用加载的
this.imagesloaded();
然而,加载的图像不是组件的一部分,也不是React中的标准。因此,this.imagesloaded是未定义的,因为它从未被声明过。尝试删除语句中的"this"部分。
imagesLoadedFunc: function() {
imagesloaded();
//the rest of the method
},