Most efficient way to pass parameters in onClick handler

后端 未结 4 385
生来不讨喜
生来不讨喜 2021-01-02 04:09

I am using inline arrow function to change the onClick handlers of some divs in my React component, but I know it is not a good way in terms of performance.

相关标签:
4条回答
  • 2021-01-02 04:20

    The best way currently is to wrap your event handler in useCallback hook as it will prevent your handler function from being created each time render is called.

    import React, { useCallback } from 'react'
    
    const MyComponent = ({ changeRoute }) => {
      const eventHandler = useCallback(() => {
        changeRoute('page1')
      }, [changeRoute])
    
      return (
        <div onClick={eventHandler}>1</div>
      )
    }
    

    For more info check - useCallback docs

    0 讨论(0)
  • 2021-01-02 04:32

    You can add a data to your div:

    <div data-id={1} onClick={this.changeRoute}>1</div>
    

    Then you can retrieve that data in your onClick handler:

    onClick = (event) => {
      const id = event.currentTarget.dataset.id;
    }
    
    0 讨论(0)
  • 2021-01-02 04:37

    #1 is fine.

    #2 is also 'fine', but you need to pass props, then the render function will look exactly like #1. You will be calling the bind'd function, because you replaced it in the constructor.

    #3 is just wrong, as the function gets called during render.

    And regarding #4, from react docs

    We generally recommend binding in the constructor or using the class fields syntax, to avoid this sort of performance problem.

    This causes a performance penalty when your function is used in its child components and will cause the child components to re-render (its not in your case). So you shouldn't do #4.

    0 讨论(0)
  • 2021-01-02 04:40

    You can use arrow function to define your changeRoute handler.

    This is known as Class field syntax. More on it here in official react docs.

    constructor() {
      super(props)
    }
    
    changeRoute = (parameter) => (event) => {
        // business logic for route change.
    }
    

    Then you can use this function directly like so:

    render() {
      return (
        <>
          <div onClick={changeRoute(params1)}>1</div>
          <div onClick={changeRoute(params2)}>2</div>
        </>
      )
    }
    

    You do not have to worry about the binding. Arrow functions inherit their parent's this.

    0 讨论(0)
提交回复
热议问题