简体   繁体   中英

React, pass prop as function argument

<div id="board" onClick={(event) => 
                         this.props.boardClicked(event)}>

I would like to pass a second argument trying something like this, but my syntax is off I think:

<div id="board" 
   onClick={(event, {this.props.activeCharacter}) =>
            this.props.boardClicked(event, {this.props.activeCharacter})}>

Simple change would be that because you are using an arrow function it is lexically bound automatically to the react compmponent instance, so you can use this within function. Simply pass as an extra arg from within the function

<div id="board" onClick={(event) => this.props.boardClicked(event, this.props.activeCharacter)}>

Using arrow functions in event handlers in react is a bad idea though because it creates an anonymous function, that will cause this component to unnecessarily always re-render which can hurt performance if component is used a lot

You can overcome that by defining a handler on your class

onBoardClick = (event) => this.props.boardClicked(event, this.props.activeCharacter)

render = () => <div id="board" onClick={this.onBoardClick} />

Now you are passing the same function reference each time so no unnecessary re-renders but same click handler functionality

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