2016-08-17 318 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> 
    ); 
    } 
}