this .clicked("hello】."/> this .clicked("hello】.">

Home >Web Front-end >JS Tutorial >How to write click event in react

How to write click event in react

coldplay.xixi
coldplay.xixiOriginal
2020-11-19 11:00:243890browse

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>
    )
}
...

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>
    )
}
...

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>
    )
}
...

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!

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