# React Event Handler 命名慣例 ## TL;DR: ```js <MyComponent onClick={handleClick} /> ``` ## TL;DR: ```js <MyComponent onClick={handleClick} /> ``` ## Prop Name ``` on[TargetName]EventName[PayloadType] ``` - `EventName`: 事件名稱,例如 `Click` -> `onClick`,`Press` -> `onPress`,`Change` -> `onChange`,`Submit` -> `onSubmit`。 - `TargetName`: Optional,如果一個 component 有多個會觸發事件的元素,這裡就會放元素的名稱,例如變成 `onLoveIconPress`、`onRemoveButtonClick`、`onDescriptionChange`、`onSelectionChange` ([React Native - TextInput](https://facebook.github.io/react-native/docs/textinput#onselectionchange))。 - `PayloadType`: 如果傳送給 event handler 的 payload (或說,event handler function 的 argument) 不是一個標準的 Event 或如慣例的 Event Object,這裡就會放 payload 的型別,例如 `onChangeText` ([React Native - TextInput](https://facebook.github.io/react-native/docs/textinput#onchangetext))。 ## Function Name 如 prop name,但把 `on` 改成 `handle[ElementName]`,optional 的 `ElementName` 是用來識別這個 event handler function 是被用來 handle 哪個 element 用的。例如: - `onClick` -> `handleLikeButtonClick` (`<LikeButton onClick={handleLikeButtonClick} />`) - `onChangeText` -> `handleTitleChangeText` (`<TextInput style={styles.titleTextInput} onChangeText={handleTitleChangeText} />`) ## 參考資料 - [Event Handler Naming in React | Jake Trent](https://jaketrent.com/post/naming-event-handlers-react/) - [eslint-plugin-react/jsx-handler-names.md at master · yannickcr/eslint-plugin-react · GitHub](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-handler-names.md)