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> ); } }