--- tags: react, disqus: hackmd --- ###### tags: `react` # React 點擊事件 [React onClick Event Handling](https://upmostly.com/tutorials/react-onclick-event-handling-with-examples#call-function-after-clicking-button) [官方 - 事件處理](https://zh-hant.reactjs.org/docs/handling-events.html) ### 點擊執行函示 範例為點擊button後執行`sayHello`這個函示。 ```javascript= // class component import React, { Component } from 'react'; class App extends Component { constructor(props) { super(props); this.sayHello = this.sayHello.bind(this); } sayHello() { alert('Hello!'); } return ( <button onClick={this.sayHello}> Click me! </button> ); } export default App; ``` ```javascript= // functional component import React from 'react'; function App() { function sayHello() { alert('Hello!'); } return ( <button onClick={sayHello}> Click me! </button> ); } export default App; ``` 常犯的錯誤 ```javascript= // Good <button onClick={sayHello}> Click me! </button> ``` ```javascript= // Bad <button onClick={sayHello()}> Click me! </button> ``` 其實主要看起來,不管是class或functional的component,寫在按鈕上的點擊觸發事件都不會帶有`()括號`,因為如果帶有()那每次component render的時候都會重複建立這個事件函示。 ### 點擊執行內聯函示(inline function) 說是inline function,你可以看到他撰寫的方法是`arrow function` ```javascript= import React from 'react'; function App() { return ( <button onClick={() => alert('hello'))}> Click me! </button> ); } export default App; ``` 常犯的錯誤 ```javascript= // Good <button onClick={() => functionName())}> Click me! </button> ``` ```javascript= // Bad <button onClick={() => functionName}> Click me! </button> ``` 不同於上面的`點擊執行函示`,inline function則是要帶`()括號`。 內聯函示,比較不推薦,原因上面也有帶到,就會建立一個不同的callback,如果這個 callback 被當作一個 prop 傳給下層的 component 的話,其他的 component 也許會做些多餘的 re-render。 ### 如果你是class component 如果你是class component又不想在constructor bind事件,那你還可以使用`class field`語法。 ```javascript= class LoggingButton extends React.Component { // 這個語法確保 `this` 是在 handleClick 中被綁定: // 警告:這是一個還在*測試中*的語法: handleClick = () => { console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } } ``` ### 將參數傳給 Event Handler ```javascript= <button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> <button onClick={this.deleteRow.bind(this, id)}>Delete Row</button> <button onClick={() => this.deleteRow(a, b, c)}>Delete Row</button> ``` 以上這兩行程式是相同的。一個使用`arrow functions`,另一個則使用了`Function.prototype.bind`。 我個人覺得,他們都帶了`()括號`,所以理論上應該會有上面提到的re-render問題。 可以試試用下面這個方法寫,不過如果你要傳的不只`e`這個參數,那可能也是要用arrow function的方式去做。 ```javascript= function ActionLink() { function handleClick(e) { e.preventDefault(); console.log('The link was clicked.'); } return ( <a href="#" onClick={handleClick}> Click me </a> ); } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up