2015-11-07 79 views
6

使用ES6時反應0.14是否有避免樣板的方法?React僅將組件方法綁定到此 - 解決方法?

到現在爲止,我不必擔心我的函數被綁定到我創建的Component,但這不再是(爲什麼?!?)的情況和Component僅限於Component超類(If我正確理解錯誤)。

所以我真的需要每個創建一個新的類就是這個代碼添加到構造時間做:

class CustomComp extends React.Component { 

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

    newFunction(){ 
    console.log('This is user defined function'); 

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

所以,如果我不會綁定newFunction它會失敗(無道具,狀態或任何)。

有沒有辦法解決這個問題?

+0

https://medium.com/@john1jan/react-binding-revealed-aa458df8c136#.fd5z0vmjl – John

回答

5

React documentation

沒有自動綁定

方法遵循相同的語義規則ES6類,這意味着 它們不會自動綁定到這個實例。你必須明確地使用.bind(this)或者arrow functions =>來使用 。

因此,不,沒有一種自動方式來綁定0.14中新增的所有方法。但是,正如文檔建議,用戶可以:

1)使用箭頭功能(但是,如果使用的是巴別,需要階段0)

class CustomComp extends React.Component { 

    constructor() { 
    super(); 
    } 

    newFunction =() => { 
    console.log('This is user defined function'); 

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

2),則可以在地方綁定

class CustomComp extends React.Component { 

    constructor() { 
    super(); 
    } 

    newFunction() { 
    console.log('This is user defined function'); 

} 
    render() { 
    return <button onClick={this.newFunction.bind(this)}>Click</button> 
    } 
} 

3)您可以使用AR代替行功能(這是如結合):

class CustomComp extends React.Component { 

    constructor() { 
    super(); 
    } 

    newFunction() { 
    console.log('This is user defined function'); 

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

我傾向於使用數2 & 3如果我只有一個1-2的方法。數字1是好的,但你必須記住每個方法定義的語法。如果我有很多方法,我確實傾向於在構造函數中綁定。

+1

很好的答案。只需稍微提示一下:你可以跳過額外的{{}'集合,然後直接寫'onClick = {()=> this.newFunction()}'。 – naomik

+0

@naomik是的。你是對的。編輯。謝謝。 –

+0

很好的答案。謝謝。 – Shikloshi

相關問題