admin管理员组

文章数量:1410724

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?

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?

Share Improve this question asked Nov 13, 2018 at 10:32 user3432681user3432681 6644 gold badges12 silver badges27 bronze badges 2
  • onClick={(e) => this.itemClick(item, e)}or onClick={this.itemClick.bind(this, item)} – Mayank Shukla Commented Nov 13, 2018 at 10:34
  • This has to do with the binding on "this". See Handling Events on React for further information about event handling and this for further information about binding in functions. – Agash Thamo. Commented Nov 13, 2018 at 10:36
Add a ment  | 

1 Answer 1

Reset to default 7

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)}>

本文标签: javascripthow to call function with parameter in JSXStack Overflow