React onClick - pass event with parameter

╄→гoц情女王★ 提交于 2019-11-30 10:39:47

问题


Without Parameter

function clickMe(e){
  //e is the event
}

<button onClick={this.clickMe}></button>

With Parameter

function clickMe(parameter){
  //how to get the "e" ?
}
<button onClick={() => this.clickMe(someparameter)}></button>

I want to get the event. How can I get it?


回答1:


Try this

<button onClick={(e) => {
     this.clickMe(e, someParameter)
}}>Click Me!</button>

And in your function

function clickMe(event, someParameter){
     //do with event
}



回答2:


With the ES6, you can do in a shorter way like this:

const clickMe = (parameter) => (event) => {
    // Do something
}

Ans use it:

<button onClick={clickMe(someParameter)} />



回答3:


Solution 1

function clickMe(parameter, event){
}

<button onClick={(event) => {this.clickMe(someparameter, event)}></button>

Solution 2 Using the bind function is considered better, than the arrow function way, in solution 1. Note, that the event parameter should be the last parameter in the handler function

function clickMe(parameter, event){
}

<button onClick={this.clickMe.bind(this, someParameter)}></button>



回答4:


To solve the creating new callback issue completely, utilize the data-* attributes in HTML5 is the best solution IMO. Since in the end of the day, even if you extract a sub-component to pass the parameters, it still creates new functions.

For example,

const handleBtnClick = e => {
  const { id } = JSON.parse(e.target.dataset.onclickparam);
  // ...
};

<button onClick={handleBtnClick} data-onclickparam={JSON.stringify({ id: 0 })}>

See https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes for using data-* attributes.



来源:https://stackoverflow.com/questions/42597602/react-onclick-pass-event-with-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!