React(5) --綁定函數事件
阿新 • • 發佈:2018-12-09
ets 頁面加載 str 成員方法 pan name home 寫法 pro
綁定函數事件
在以類繼承的方式定義的組件中,為了能方便地調用當前組件的其他成員方法或屬性(如:this.state),通常需要將事件處理函數運行時的 this 指向當前組件實例。
run(){
alert(‘我是一個run方法‘)
}
<button onClick={this.run}>執行方法</button>
//方法不需要加(),加了(),一旦頁面加載進來就執行了
綁定事件處理函數this的幾種方法:
方法1:
run(){ alert(this.state.name) } <button onClick={this.run.bind(this)}>按鈕</button> //不綁定this的話,上面的方法裏面的this就指向不了,拿不到數據
方法2:
constructor(props){ super(props); //固定寫法 this.state={ name:‘我是一個home組件‘ } //構造函數中改變 this.run = this.run.bind(this); } run(){ alert(this.state.name) } <button onClick={this.run}>按鈕</button>
方法3:
//直接使用箭頭函數
run=()=> { alert(this.state.name) } <button onClick={this.run}>按鈕</button>
函數方法裏傳值,改變state的值
setName=(str)=>{ //改變state的值 this.setState({ username:str }) }
<button onClick={this.setName.bind(this,‘張三‘)}>執行方法傳值</button> <button onClick={this.setName.bind(this,‘張三‘,‘李四‘)}>執行方法傳值</button>
React(5) --綁定函數事件