先看例子
import React from 'react';
import ReactDOM from 'react-dom';
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn: true
};
//this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// console.log(this)
this.setState(
{
isToggleOn: false
})
}
render() {
//console.log(this)
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
但是點擊按鈕的時候,報錯了。
按上圖的打印this,只有在構造函數,將handleClick通過bind綁定this,handleClick()函數裏的this才能指向Toggle。
當然render函數裏this一直指向Toggle。
總之handleClick中的this沒有指向Toggle,所以this.setState方法也就不存在了。
所以要使用this.handleClick = this.handleClick.bind(this);
那麼,爲什麼onClick={this.handleClick},this指向變了呢。
看看官方給出的解釋
接下來完善這個代碼
import React from 'react';
import ReactDOM from 'react-dom';
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn: true
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(
{
isToggleOn: this.state.isToggleOn?false:true
})
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
接下里看如何向事件處理函數傳遞參數
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
測試如下
<button onClick={this.handleClick.bind(this,123)}>
handleClick(i) {
console.log(i)//結果123
}
另一種方式
<button onClick={(e)=>this.handleClick(123,e)}>
handleClick(i) {
console.log(i)
}