在使用 React 中的 Class extends寫法,如果 onClick
綁定一個方法就需要 bind(this)
,如果使用React.createClass
方法就不需要
解析:
React.createClass
是ES5 的寫法默認綁定了 bind 寫法
在 ES6 中新增了class,綁定的方法需要綁定 this,如果是箭頭函數就不需要綁定 this
示例:
第一種寫法:
_handleClick(e){
console.log(this);
}
render(){
return (
<div><h1 onClick={this._handleClick.bind(this)}>點擊<h1></div>
)
}
第二種寫法:
constructor(props){ super(props); this._handleClick=this._handleClick.bind(this) } _handleClick(e){e}{ console.log(this); } render(){ return( <div><h1 onClick={this._handleClick}>點擊</h1></div> ) }
第三種寫法:
_handleClick=(e)=>{
//使用箭頭函數
console.log(this);
}
render(){
return (
<div><h1 onClick={this._handleClick}>點擊</h1></div>
)
}