Andy's blog

If you always do what you've always done, you'll always get what you've always got.

0%

筆記-React Event Handlers

前言:
紀錄一下 React 筆記。


參考資料:


  1. React 事件命名會以 handle 開頭
  2. 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

  1. inline anonymous function
    1
    <button onClick={() => handleClick()}>
  2. pass a function
    1
    <button onClick={handleClick}>
  3. pass a function
    1
    2
    3
    <button onClick={function handleClick(){
    alert('click');
    }}>

Conclusion

  1. Don’t execute function instead you should pass function

Event handlers as props

  1. usually start with on and followed by a capital letter
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    export function PlayButton({ onPress , children}){

    return (
    <button onClick={onPress}>
    {children}
    </button>
    )
    }

    export function App(){
    return(
    <PlayButton onPress={() => alert('hi')}>
    hihihihihi
    </PlayButton>
    )
    }

Event stopPropagation

  1. 阻止事件冒泡
  2. 要在捕獲階段下 stopPropagation