我用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并不太熟悉,仍然希望进一步改善自己。
答案 0 :(得分:4)
你需要绑定勾选
constructor() {
super();
this.state = {start: 15}
this.tick = this.tick.bind(this)
}
答案 1 :(得分:0)
你需要绑定你的刻度函数:
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