Pass the event object and other parameters at the same time in the React event handler

1. No other parameters

return <a href="https://imooc.com/" onClick={this.clickHandler}>
            click me
       </a>

//当我们没有传任何参数的时候还是可以使用event,即默认追加了一个event参数
clickHandler = (event) => {
        event.preventDefault() // 阻止默认行为
        event.stopPropagation() // 阻止冒泡
}

2. Pass event and other parameters at the same time

  // 最后追加一个参数,即可接收 event
  clickHandler(id, title, event) {

    console.log(id, title)       // 2 "按钮"
    console.log('event', event)   //event Class {…}

  }
  
  render(){ 
  return(
    <button onClick={this.clickHandler.bind(this,2, '按钮')}>点我</button>
  )
  
  }

The screenshot of the console output is as follows:

3. The difference between the two methods of arrow function passing parameters and bind passing parameters

<button onClick = { (e)=> this.handleClick( id,e ) }></button>
<button onClick = { this.handleClick.bind( this,id ) }></button>

The above two methods are equivalent, 箭头函数 and Function.prototype.bind are implemented by and  respectively  .

In the above two cases, the React event object  e will be passed as the second parameter.

If the arrow function is used, the event object must be passed explicitly,

By  bind the way, the event object and more parameters will be implicitly passed.

You can see another article of mine for comparing native js transfer parameters

 

 

Guess you like

Origin blog.csdn.net/a1059526327/article/details/106841401