2 回答

TA貢獻1802條經(jīng)驗 獲得超6個贊
如果你的點擊事件觸發(fā)的方法里需要引用this。就需要綁定啊。不然你的this是null(記得如果沒綁定this應(yīng)該是全局window。但這里this 就是null,擼完手上的需求去看一下react源碼 )
所以 你要么在創(chuàng)建的時候綁定:
<div className="save" onClick={this.handleClick.bind(this)}>Save</div>
要么在一開始構(gòu)造器里聲明綁定
constructor(props){
super(props);
this.handleClick=this.handleClick.bind(this)
還有一種是利用閉包把作用域包起來
<div className="save" onClick={()=>this.handleClick}>Save</div>
如果用第一種 會在每次點擊時通過bind創(chuàng)建一個新的方法,所以一般用2 3 兩種情況,顯示調(diào)用bind()只是為了保證this值。

TA貢獻2011條經(jīng)驗 獲得超2個贊
官方推薦的是在constructor中bind,或者箭頭函數(shù)class屬性初始化語法。
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
class LoggingButton extends React.Component {
// This syntax ensures `this` is bound within handleClick.
// Warning: this is *experimental* syntax.
handleClick = () => {
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
- 2 回答
- 0 關(guān)注
- 791 瀏覽
添加回答
舉報