2016-08-17 323 views
0

当我们有一些参数传入方法时,我对理解jsx-no-bind有些困难。react/jsx-no-bind:如何通过参数

我的代码工作正常:

class Foo extends React.Component { 
    foo(reverse, e) { 
    if(reverse) { 
     //smthg to do with e.target 
    } else { 
     //smthg to do with e.target 
    } 
    // call this.bar() 
    } 

    bar() { 
    //smthg 
    } 

    render() { 
    return (
     <button type="button" onClick={this.foo.bind(this, false)}>go</button> 
     <button type="button" onClick={this.foo.bind(this, true)}>reverse</button> 
    ); 
    } 
} 

但我已经JSX-没有绑定我的棉短绒。

如何使用正确的方式使用:

constructor() { 
    super(); 
    this.foo = this.foo.bind(this); 
} 

但是......在经过一些ARGS。就我而言,我想通过“反向”的论点。

在此先感谢,

回答

0
constructor() { 
    super(); 
    this.foo = this.foo.bind(this); 
} 

这应该只是罚款。稍后当您拨打this.foo(true)this.foo(false)时,该功能将正确绑定到该实例。

根据您的transpiler /栈,你可以利用箭头的功能,使其更快:

class Foo extends React.Component { 
    foo = (reverse, e) => { 
    // ... 
    } 
} 
+0

当我打电话: <跨度的onClick = {this.foo(真)}>去 <跨度的onClick = {this.foo(假)}>反向 执行是瞬间。该功能被执行并出现错误。 组件正在渲染时。 –

+0

你是对的我误解了你的问题。要做到这一点,你必须在渲染中进行绑定,或绑定2个独立的函数。 'this.fooTrue = this.foo.bind(this,true)'...说实话,基于你的按钮中的文字,去/倒,我会说他们应该可能是2个独立的函数。 – rfunduk

+0

好吧,我会让渲染中的绑定函数。实际上,“去/倒”就是这个例子^^但是,谢谢你的回答和时间! –

0

这解决了部分applicated功能:

class Foo extends React.Component { 
    constructor() { 
    super(); 
    this.foo = this.foo.bind(this); // Bind the function as usual 
    } 

    foo(reverse, e) { 
    return() => { // Here you're returning a new function wrapping the original function 
     if(reverse) { 
     //smthg to do with e.target 
     } else { 
     //smthg to do with e.target 
     } 
     // call this.bar() 
    } 
    } 

    render() { 
    return (
     <button type="button" onClick={this.foo(false)}>go</button> // Execute the function here with the argument 
     <button type="button" onClick={this.foo(true)}>reverse</button> 
    ); 
    } 
}