2015-12-14 84 views
12

本週末我掠奪了一些最近的反應回購,並且我遇到了一個使用ES6類語法的組件組合的例子,它有點像這樣。神祕的語法onClick = {:: this.submit}

class MyThing extends Component { 
     constructor(props) { 
     super(props) 
     this.state = {something: 'the thing'} 
     } 

     submit() { 
     // do stuff 
     } 

     render() { 
     <div> 
      <button onClick={::this.submit}>Fire Submit</button> 
     </div> 
     } 
    } 

通知代替this.submit.bind(this)

它的作品,我不能對這個功能在任何地方找到文檔,我覺得自己像一個瘋狂的人::this.submit,這是什麼onClick={::this.doSomethingInsideRenderWithoutDotBind}語法打來電話,我在哪裏可以閱讀更多關於它?

+12

https://github.com/zenparsing/es-function-bind – Quentin

+1

@Quentin就是這樣!你很棒,非常感謝。我會接受這個答案,在你的閒暇時間。 – James

+2

請記住,這是一個階段0的功能,這意味着要實現標準化還有很長的路要走。有趣的知道,但最好避免在你自己的代碼。 –

回答

2

雙冒號是詳細的here,目前是ES7提案,所以它還沒有確定下來,對此仍有很多爭議。它也不允許傳遞參數。所以如果你有這種需求,它的使用有限。

還存在詞彙結合這次「胖箭頭」功能選項(在實際的使用功能,而不是對它的調用)...

// Basic syntax: 
(param1, param2, paramN) => { statements } 
(param1, param2, paramN) => expression 
    // equivalent to: => { return expression; } 

// Parentheses are optional when there's only one argument: 
(singleParam) => { statements } 
singleParam => { statements } 

// A function with no arguments requires parentheses: 
() => { statements } 

// Advanced: 
// Parenthesize the body to return an object literal expression: 
params => ({foo: bar}) 

// Rest parameters are supported 
(param1, param2, ...rest) => { statements }