当使用es6 bind与react时,将arg传递给函数

时间:2017-01-11 09:50:08

标签: javascript reactjs ecmascript-6

如果我在JSX中使用es6箭头功能,如果我有来自其他组件的道具,我可以通过我的args这样的。

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

我怎样才能通过参数?

2 个答案:

答案 0 :(得分:0)

你在这一行中犯了错误

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

这应该有效:

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

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

答案 1 :(得分:0)

你不能像第一个那样直接传递。但您可以使用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>
      )
  }
})