简体   繁体   中英

Binding vs arrow-functions performance in React

Are there any pros and cons for using the methods below to call a function in react ? Or are they the same?

Method 1

 const ComponentA = () => { const handleClick = (something) => { console.log(something) } return <div onClick={() => handleClick("Hello world")} /> }

Method 2

 const ComponentA = () => { const handleClick = (something) => { console.log(something) } return <div onClick={handleClick.bind(this, "Hello world")} /> }

To begin I'll give a quick definition of what this is in React. this in general refers to a JavaScript element depending on the scope or context of its use. So in React, when we define classes we use methods inside those classes to refer to attributes such as state and props. For our methods to have access to this.state and this.props we need to bind the React component this context to those methods. Binding this to the class methods enables us to access props and state for the component with this.props and this.state. A benefit of using arrow functions is that this is already bound to that function so we don't need to specify that anywhere else.

Both the methods are correct, the only difference is that the lines of code reduces if you use arrow function syntax rather than old function syntax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM