this.deleteRow(id, e)}"; 2. Pass by "{this.deleteRow.bind(this, id)}" ."/> this.deleteRow(id, e)}"; 2. Pass by "{this.deleteRow.bind(this, id)}" .">
Home >Web Front-end >JS Tutorial >How to pass event object in react
Methods for passing event objects in react: 1. Use "{(e) => this.deleteRow(id, e)}" to pass; 2. Pass "{this.deleteRow.bind(this , id)}" method.
The operating environment of this tutorial: windows7 system, react17.0.1 version, Dell G3 computer.
Recommended: "Javascript Basics Tutorial"
Pass parameters (event object) to the event handler
Pass to the function Additional parameters: The following two methods
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> <button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
The above two methods are equivalent and are implemented through arrow functions and Function.prototype.bind respectively.
In the above two examples, parameter e as the React event object will be passed as the second parameter. Through arrow functions, the event object must be passed explicitly, but through bind, the event object and more parameters will be passed implicitly.
It is worth noting that when passing parameters to the listening function through the bind method, for the listening function defined in the class component, the event object e must be ranked behind the passed parameters, for example:
class Popper extends React.Component{ constructor(){ super(); this.state = {name:'Hello world!'}; } preventPop(name, e){ //事件对象e要放在最后 e.preventDefault(); alert(name); } render(){ return ( <div> <p>hello</p> {/* Pass params via bind() method. */} <a href="https://reactjs.org" onClick={ this.preventPop.bind(this,this.state.name) }>Click</a> </div> ); } }
For more programming-related knowledge, please visit: programming learning! !
The above is the detailed content of How to pass event object in react. For more information, please follow other related articles on the PHP Chinese website!