前言:
紀錄一下 React
筆記。
參考資料:
- React 事件命名會以
handle
開頭 - Usually defined inside components
Pitfall
1 | <button onClick={handleClick()}> |
JavaScript inside the JSX {}
executes immediately
Therefore, this will not have any interaction with your UI
Correct Way
- inline anonymous function
1
<button onClick={() => handleClick()}>
- pass a function
1
<button onClick={handleClick}>
- pass a function
1
2
3<button onClick={function handleClick(){
alert('click');
}}>
Conclusion
- Don’t execute function instead you should pass function
Event handlers as props
- usually start with
on
and followed by a capital letter1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16export function PlayButton({ onPress , children}){
return (
<button onClick={onPress}>
{children}
</button>
)
}
export function App(){
return(
<PlayButton onPress={() => alert('hi')}>
hihihihihi
</PlayButton>
)
}
Event stopPropagation
- 阻止事件冒泡
- 要在捕獲階段下 stopPropagation