[英]React Component not working with ES6
我用React编写了这个Timer组件,可以在es5上使用,但是由于某些原因,它在es6上不可用。
class Timer extends React.Component{
constructor() {
super();
this.state = {start: 15}
}
tick() {
this.setState ({start: this.state.start - 1});
}
componentDidMount() {
this.interval = setInterval(this.tick, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <h1> Time here: {this.state.start}</h1>
}
}
ReactDOM.render(<Timer />, document.getElementById('app'));
值得一提的是,我不太熟悉React,仍然希望自己进一步提高自己。
您需要绑定刻度
constructor() {
super();
this.state = {start: 15}
this.tick = this.tick.bind(this)
}
您需要绑定您的tick函数:
class Timer extends React.Component{
constructor() {
super();
this.state = {start: 15}
}
tick() {
this.setState ({start: this.state.start - 1});
}
componentDidMount() {
this.interval = setInterval(this.tick.bind(this), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <h1> Time here: {this.state.start}</h1>
}
}
React.render(<Timer />, document.getElementById('container'));
这是jsfiddle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.