繁体   English   中英

使用 es6 绑定与反应时将 arg 传递给函数

[英]pass arg to function when using es6 bind with react

如果我在 JSX 中使用 es6 箭头函数,我可以像这样传递我的参数,如果我有来自另一个组件的道具。

class MyComponent extends Component({
  myFunc(param){
    console.log(param);
  }
   render(
    return(
      <button onClick="(param)=>myFunc(param)"></button>
    )
  )
})

但是如果我你用这种

class MyComponent extends Component({
  constructor(){
    this.myFunc = this.myFunc.bind(this);
  }
  myFunc(){

  }
   render(
    return(
      <button onClick={this.myFunc}></button>
    )
  )
})

我怎样才能传递参数?

你在这一行犯了错误

constructor(){
  this.myFunc = myFunc.bind(this);
}

这应该有效:

constructor(){
  this.myFunc = this.myFunc.bind(this);
}

myFunc(props){
  console.log(props);
}

你不能像第一个那样直接通过。 但是您可以使用e.target以不同的方式访问。 但我不确定你想要什么样的场景。

class MyComponent extends Component({
   constructor(){
       this.myFunc = this.myFunc.bind(this);
   }
   myFunc(e){
     console.log(e.target.arg);
   }
   render(){
      return(
         <button arg={yourargument} onClick={this.myFunc}></button>
      )
  }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM