javascript - reactjs麻烦看一下这段代码哪里错了?
本文介绍了javascript - reactjs麻烦看一下这段代码哪里错了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
let INTERVAL = 2000;
class AnimateDemo extends React.Component{
constructor(props) {
super(props);
this.state = {
current: 0
};
}
componentDidMount() {
this.interval = setInterval(this.tick, INTERVAL);//不知道是这部分出错
}
componentWillUnmount() {
clearInterval(this.interval);
}
tick() {
this.setState({current: this.state.current + 1});//还是这部分出错
}
render() {
let children = [];
let pos = 0;
let colors = ['red', 'gray', 'blue'];
for (let i = this.state.current; i < this.state.current + colors.length; i++) {
let style = {
left: pos * 128,
background: colors[i % colors.length]
};
pos++;
children.push(<div key={i} className="animateItem" style={style}>{i}</div>);
}
return (
<CSSTransitionGroup
className="animateExample"
transitionEnterTimeout={250}
transitionLeaveTimeout={250}
transitionName="example">
{children}
</CSSTransitionGroup>
);
}
}
出错信息是
Uncaught TypeError: Cannot read property 'current' of undefined
解决方案
代码改改:
class AnimateDemo extends React.Component{
constructor(props) {
super(props);
this.state = {
current: 0
};
}
componentDidMount() {
this.interval = setInterval(this.tick.bind(this), INTERVAL);//就是这部分出错了,因为this在interval之内变了,需要专门绑定一下
}
componentWillUnmount() {
clearInterval(this.interval);
}
tick() {
this.setState({current: this.state.current + 1});
}
render() {
let children = [];
let pos = 0;
let colors = ['red', 'gray', 'blue'];
for (let i = this.state.current; i < this.state.current + colors.length; i++) {
let style = {
left: pos * 128,
background: colors[i % colors.length]
};
pos++;
children.push(<div key={i} className="animateItem" style={style}>{i}</div>);
}
return (
<CSSTransitionGroup
className="animateExample"
transitionEnterTimeout={250}
transitionLeaveTimeout={250}
transitionName="example">
{children}
</CSSTransitionGroup>
);
}
}
这篇关于javascript - reactjs麻烦看一下这段代码哪里错了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文