簡體   English   中英

React組件不適用於ES6

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM