简体   繁体   中英

how to call function with parameter in JSX?

I am trying to create a listitem click listener with the item as argument in React. But the function itemClick is now called when page is loaded in stead of when I click on a item.

itemClick = (item) => {
  console.log(item)
}    

render(){
        return(
            <Fragment>
                {this.state.list.map(item=> (
                   <tr onClick={this.itemClick(item)}>
                    <td>{item.firstname}</td>
                    <td>{item.lastname}</td>
                   </tr>
                ))}
            </Fragment>
        )
    }

when I do this the function will be called when i clicked but I can't get the argument

<tr onClick={this.itemClick} >

Help?

By writing this.itemClick(item) you are invoking itemClick directly on render. You can instead create a new inlined function that calls itemClick when it is invoked.

<tr onClick={() => this.itemClick(item)}>

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