简体   繁体   English

React组件不适用于ES6

[英]React Component not working with ES6

I got this Timer component written with React,that does work with es5, but for some reasons it doesn't 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'));

Need to mention that I'm not too familliar with React, still looking further to improve myself. 值得一提的是,我不太熟悉React,仍然希望自己进一步提高自己。

You need to bind tick 您需要绑定刻度

  constructor() {
    super();
    this.state = {start: 15}
    this.tick = this.tick.bind(this)
    }

You need to bind your your tick function : 您需要绑定您的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'));

Here is jsfiddle 这是jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM