Home > Web Front-end > JS Tutorial > body text

How to pass event object in react

藏色散人
Release: 2023-01-04 09:36:41
Original
2718 people have browsed it

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>
Copy after login

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>
        );
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!