The API (via 'extends React.Component') is similar to React.createClass with the exception of getInitialState. Instead of providing a separate getInitialState method, you set up your own state property in the constructor.javascript
React在ES6的實現中去掉了getInitialState這個hook函數,也就是說 經過es6類的繼承實現時 state的初始化要在constructor中聲明:java
class App1 extends React.Component { constructor(props) { super(props); this.state = {num:1}; } handleClick(){ console.log(1); this.setState({num: this.state.num + 1}); } render() { var num = this.state.num; return( <div> <button onClick={this.handleClick.bind(this)}>點我+1</button> <Link to="/test2" className="active">Hello test{num}!!!</Link> </div> ); } }
Dome:es6
class App1 extends React.Component { constructor(props) { super(props); this.state = {num:1}; } handleClick(){ console.log(1); this.setState({num: this.state.num + 1}); } render() { var num = this.state.num; return( <div> <button onClick={this.handleClick.bind(this)}>點我+1</button> <Link to="/test2" className="active">Hello test{num}!!!</Link> </div> ); } }
上面的demo中有大量this的使用,在 class App1 extends React.Component 中咱們是聲明該class,由於this具體是由其上下文決定的,所以在類定義中咱們沒法得知this用法。 至關因而new了上面定義的類,首先調用 constructor() 函數, this.state 的this上下文就是該實例對象;同理,render() 函數中 this.state.liked 的this上下文也是該對象。問題在於 onClick={this.handleClick} ,獲取該函數引用是沒有問題,這裏的this上下文就是該對象。函數
這時問題來了,在原來 React.createClass 中, handleClick() 在onClick事件觸發的時候,會自動綁定到LikeButton實例上,這時候該函數的this的上下文就是該實例。不過在ES6的class的寫法中,Facebook取消了自動綁定,實例化LikeButton後,handleClick()的上下文是div的支撐實例( backing instance ),而 handleClick() 本來要綁定的上下文是LikeButton的實例。對於該問題,咱們有多種解決方案。this
class App1 extends React.Component { constructor(props) { super(props); this.state = {num:1}; } handleClick(){ console.log(1); this.setState({num: this.state.num + 1}); } render() { var num = this.state.num; return( <div> <button onClick={this.handleClick.bind(this)}>點我+1</button> <Link to="/test2" className="active">Hello test{num}!!!</Link> </div> ); } }
class App1 extends React.Component { constructor(props) { super(props); this.state = {num:1}; } handleClick(){ console.log(1); this.setState({num: this.state.num + 1}); } render() { var num = this.state.num; return( <div> <button onClick={()=>this.handleClick()}>點我+1</button> <Link to="/test2" className="active">Hello test{num}!!!</Link> </div> ); } }