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  >  Article  >  Web Front-end  >  How to pass event object in react

How to pass event object in react

藏色散人
藏色散人Original
2020-12-09 09:45:482663browse

Methods for passing event objects in react: 1. Use "{(e) => this.deleteRow(id, e)}" to pass; 2. Pass "{this.deleteRow.bind(this , id)}" method.

How to pass event object in react

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:&#39;Hello world!&#39;};
    }
    
    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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn