語法:onclick = {this.函數名}
onClick = {this.yourEvent}
事件類型
onClick onChange onSubmit
綁定this方式
第一種:onClick = {this.yourEvent} 需要在構造函數中綁定this
第二種:onClick = {this.yourEvent.bind(this)}
第三種:onClick = {() => this.yourEvent()}
第四種:屬性初始化
clickEvent = () => {事件邏輯}
優缺點:
第一種推薦,一般都是用這種方式
第二種每次render,都會重新生產一個函數
第三種每次render,都會執行一遍方法
第四種 還是實驗性的
事件傳遞參數方式
第一種:onClick = {this.yourEvent.bind(this)}
第二種:onClick = {() => this.yourEvent()}
第三種:通過event.target屬性來獲取當前DOM對象,然后獲取屬性值得方法
實例:
import React from 'react' class BindThisDemo extends React.Component{ constructor(props){ super(props); this.bindClick = this.bindClick.bind(this); } bindClick(){ alert('我是在構造函數中綁定this') } bindClick2(){ alert('我是在綁定事件中綁定this') } bindClick3(){ alert('我是在綁定事件中 用箭頭函數的特性綁定this') } bindClick4 = () => { alert('我是利用屬性初始化 來綁定this') } bindClick5(value1,value2){ alert(value1+value2) } bindClick6(value){ alert(value) } render(){ return( <div> <button onClick = {this.bindClick}>demo1</button> <button onClick = {this.bindClick2.bind(this)}>demo2</button> <button onClick = {() => this.bindClick3()}>demo3</button> <button onClick = {this.bindClick4}>demo4</button> <button onClick = {this.bindClick5.bind(this,'參數','來自bind')}>demo5</button> <button onClick = {() => this.bindClick6('參數來自箭頭函數')}>demo6</button> </div> ) } } export default BindThisDemo;
原文鏈接:https://blog.csdn.net/weixin_34194551/article/details/91367520