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

How to write click event in react

coldplay.xixi
Release: 2020-11-30 17:17:53
Original
3812 people have browsed it

How to write click events in react: 1. Use bind binding, the code is [this.clicked.bind(this, "hello world")]; 2. Use arrow function, the code is [onClick={ (event)=>this.clicked("hello】.

How to write click event in react

The operating environment of this tutorial: windows7 system, react16 version, this method is suitable for all brands of computers .

React method of writing click events:

1. bind binding

The first parameter points to this, starting from the second parameter is the parameter received by the event function. The event object event defaults to the last parameter.

...
clicked(param,event){
    console.log(param) //hello world
    console.log(event.target.value) //按钮
}
render(){
    return (
        <React.Fragment>
            <button value="按钮" onClick={this.clicked.bind(this,"hello world")}>点击</button>
        </React.Fragment>
    )
}
...
Copy after login

Here, binding this can be written uniformly , so that the code looks neater.

...
constructor(props){
    super(props);
    this.state = {};
    this.checkMenu = this.checkMenu.bind(this);
}
clicked = (param)=>{
    return (event)=>{
        console.log(event.target.value); // 按钮
        console.log(param); // hello
    }
}
render(){
    return (
        <React.Fragment>
            <button value="按钮" onClick={this.clicked(&#39;hello&#39;)}>点击</button>
        </React.Fragment>
    )
}
...
Copy after login

2. Arrow function

If the arrow function wants to pass the event object event, it needs to use the event as a parameter in the arrow function Passed to the triggered event.

...
clicked(param,event){
    console.log(param) //hello world
    console.log(event.target.value) //按钮
}
render(){
    return (
        <React.Fragment>
            <button value="按钮" onClick={(event)=>this.clicked("hello world",event)}>点击</button>
        </React.Fragment>
    )
}
...
Copy after login

Related free learning recommendations: JavaScript (video)

The above is the detailed content of How to write click event 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!