React onClick点击事件传参三种写法


第一种

用bind绑定,调用是作为第二个参数传递,不用显示传递事件对象,定义方法时,事件对象作为最后一个参数传入

class Test extends React.Component{
  constructor(props){
    super(props)
  }
  render(){
    return(
      <button onClick={this.getParameter.bind(this,'abc')}>按钮</button>
    )
  }
  getParameter=(e,msg)=>{
    console.log(e);
    console.log(msg);
  }
}
ReactDOM.render(<Test />, document.getElementById('root'));

第二种

返回一个函数,事件对象在返回的函数中

class Test extends React.Component{
  constructor(props){
    super(props)
  }
  render(){
    return(
      <button onClick={this.getParameter('abc')}>按钮</button>
    )
  }
  getParameter=(msg)=>{
    return ()=>{
      console.log(msg);
      
    }
  }
}
ReactDOM.render(<Test />, document.getElementById('root'));

第三种

事件对象作为第二个参数传递

class Test extends React.Component{
  constructor(props){
    super(props)
  }
  render(){
    return(
      <button onClick={ e => this.getParameter(e,'abc') }>按钮</button>
    )
  }
  getParameter=(e,msg)=>{
    console.log(e);
    console.log(msg);
    
  }
}
ReactDOM.render(<Test />, document.getElementById('root'));


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM