【问题标题】:pass arg to function when using es6 bind with react使用 es6 绑定时将 arg 传递给函数
【发布时间】:2017-01-11 09:50:08
【问题描述】:

如果我在 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>
    )
  )
})

如何传递参数?

【问题讨论】:

  • 你想用这个做什么目的?是为了删除子对象之类的吗?
  • @illusionist 我可能想将一些东西传递给子组件。
  • onClick={this.myFunc.bind(this)}onClick={e =&gt; this.myFunc(e)}
  • 你可以这样使用它:&lt;button onClick={this.myFunc.bind(this,param1,param2,param3)}&gt;&lt;/button&gt; myFunc(param1,param2,param3){console.log(param1,param2,param3)} 不要在构造函数中绑定它。

标签: javascript reactjs ecmascript-6


【解决方案1】:

你在这行犯了错误

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

这应该可行:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多