我有一个图库组件,展示组件道具的图像。
图库组件一次显示1个图像,但有2个随机加载数组以用于动画目的。
一切听起来都不错,但我在控制台中收到此错误
Uncaught TypeError: Cannot read property 'currentIndex' of null
不知道为什么会这样。
以下是ViewGallery.js组件:
import React from 'react';
class ViewGallery extends React.Component {
getInitialState(){
return {
currentIndex: 0,
count: 0
};
}
generateImagesDOM(){
return imagesDOM;
}
handleClick() {
let currentIndex = this.state.currentIndex;
if(currentIndex === this.state.count - 1){
currentIndex = 0;
} else {
currentIndex ++;
}
this.setState({
currentIndex: currentIndex
});
$(this.images[currentIndex]).removeClass('active');
}
render() {
let images = this.props.images;
let startWith = this.props.startWith;
let count = this.props.count;
let imagesDOM = [];
let i = startWith || 0;
if(typeof count === 'number' && count > 0){
images = images.slice(0, count - 1);
}
let length = images.length;
if(startWith > 0 && startWith < length){
let images0 = images.slice(0, startWith);
let images1 = images.slice(startWith);
images = images1.concat(images0);
}
for ( ; i<length ; i+=1 ) {
let className = "image";
if(i === this.state.currentIndex){
className += " active";
}
imagesDOM.push(<div className={className}><img src={images[i]} /></div>);
}
this.state.count = length;
return <div className="gallery" onClick={this.handleClick}>{imagesDOM}</div>
}
}
ViewGallery.propTypes = {
images: React.PropTypes.array.isRequired,
startWith: React.PropTypes.number,
count: React.PropTypes.number
}
export default ViewGallery;
答案 0 :(得分:1)
使用class
模式创建React组件时,应该在构造函数中设置初始状态,而不是getInitialState()
。
class ViewGallery extends React.Component {
constructor(props) {
super(props);
this.state = {
currentIndex: 0,
count: 0
};
}
/* rest of your code */
}
此外,与以前的createClass
模式不同,您的方法不再自动绑定组件实例,您必须自己绑定它们。之一:
onClick={this.handleClick.bind(this)}
或
onClick={e => this.handleClick(e)}
有关extends React.Component
和React.createClass()
组件创建模式之间的差异,请参阅this blog post from 2015 January。