React(5) --繫結函式事件
阿新 • • 發佈:2018-12-09
繫結函式事件
在以類繼承的方式定義的元件中,為了能方便地呼叫當前元件的其他成員方法或屬性(如: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>