?
目錄
?1、錯誤寫法?:onClick={this.acceptAlls()}
?2、正確寫法?:onClick={this.acceptAlls}(不帶括號)
總結
方案1:構造函數綁定
方案2:箭頭函數包裝方法(更簡潔)
方案3:直接綁定 + 參數傳遞
方案的關鍵區別說明
在寫代碼時,看到別人寫的點擊事件,大家寫法都不太一樣,到底有什么需要注意的呢?
-----------需要注意 ?正確的綁定方式? 和 ?事件觸發時機
?1、錯誤寫法?:
onClick={this.acceptAlls()}
?????原因:
- 這樣寫會?立即執行??
acceptAlls
?函數,而不是在點擊時執行。- 括號?
()
?表示函數調用- 組件渲染時就會執行?
acceptAlls
onClick
?實際上接收到的是?acceptAlls
?的返回值(這里是?undefined
),而不是函數本身// 例如:錯誤的寫法 class MyComponent extends React.Component {acceptAlls = () => {console.log("執行邏輯", this.props); //}; }<Button onClick={this.acceptAlls() }>保存</Button>
?2、正確寫法?:
onClick={this.acceptAlls}
(不帶括號)// 改正后的: class MyComponent extends React.Component {acceptAlls = () => {console.log("執行邏輯", this.props); //}; }<Button onClick={this.acceptAlls}>保存</Button>
總結
在 React 中,
onClick
?需要接收一個?函數引用?(即函數本身),而不是函數的執行結果
- ?
onClick={函數}
?:傳遞函數引用,點擊時執行。- ?
onClick={函數()}
?:立即執行函數,傳遞返回值(通常是無效的)。- 這里?
() => {...}
?創建了一個新函數,點擊時才會調用?acceptAlls(id)
方案1:構造函數綁定
<Button onClick={this.acceptAlls }>保存</Button>
上述寫法的前提需要:this指向要明確(要么手動綁定、要么寫成箭頭函數)
class MyComponent extends React.Component {// 方式1:構造函數中綁定constructor(props) {super(props);this.acceptAlls = this.acceptAlls.bind(this); // !!!!!!}acceptAlls() {console.log("執行邏輯", this.props); // this 正確指向組件實例}<Button onClick={this.acceptAlls}>直接確認</Button > }
或
class MyComponent extends React.Component {// 方式2:箭頭函數自動綁定 thisacceptAlls = () => {console.log("執行邏輯", this.props); // this 始終正確};<Button onClick={this.acceptAlls}>直接確認</Button > }
或
class MyComponent extends React.Component {constructor(props) {super(props);this.acceptAlls = this.acceptAlls.bind(this); // ? 正確綁定}acceptAlls(id) {console.log("執行ID:", id, this.props); // ? this 正確}render() {return (<Button onClick={() => this.acceptAlls(item.id)}>確認</Button>// ? 箭頭函數傳參 + 已綁定的方法);} }
方案2:箭頭函數包裝方法(更簡潔)
class MyComponent extends React.Component {// 箭頭函數自動綁定 thisacceptAlls = (id) => {console.log("確認操作", id, this.props);};render() {return (<div>{/* 無參數 */}<Button onClick={this.acceptAlls}>直接確認</Button >{/* 有參數 */}// 需要傳遞額外參數時(如 id):<Button onClick={() => this.acceptAlls(item.id)}>確認</Button></div>);} }
注意:
- 箭頭函數一定的性能影響?,每次渲染都會創建新函數,可能影響性能(在循環或純組件中慎用)?
方案3:直接綁定 + 參數傳遞
class MyComponent extends React.Component {constructor(props) {super(props);this.acceptAlls = this.acceptAlls.bind(this);}acceptAlls(id) { /*...*/ }render() {return (<Button onClick={this.acceptAlls.bind(this, item.id)}>確認</Button>// ? bind 直接綁定參數(注意性能影響));} }
方案的關鍵區別說明
方案 this
?綁定參數傳遞 性能影響 構造函數綁定 手動綁定 需箭頭函數傳參 最優 箭頭函數方法 自動綁定 可箭頭函數傳參 較優 直接bind傳參 手動綁定 bind直接傳參 較差(每次渲染新建函數) 最佳實踐建議
- ?優先使用方案2(箭頭函數方法)?:既解決
this
問題,又保持代碼簡潔- ?需要兼容舊代碼時用方案1?:顯式綁定更易理解
- ?避免在render中直接bind?(方案3):可能引發性能問題
?
?