第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

react事件處理為什么推崇顯式調(diào)用 bind

react事件處理為什么推崇顯式調(diào)用 bind

慕勒3428872 2019-03-22 19:14:41
react事件處理為什么推崇顯式調(diào)用 bind
查看完整描述

2 回答

?
呼啦一陣風(fēng)

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值。

查看完整回答
反對 回復(fù) 2019-03-26
?
森林海

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



查看完整回答
反對 回復(fù) 2019-03-26
  • 2 回答
  • 0 關(guān)注
  • 791 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號