2017-06-02 25 views
0

我在我的代碼中有一個語法錯誤,我不知道爲什麼。這是否與我使用的參考方式有關?爲什麼我的React組件類中有語法錯誤?

export default class ToggleMenu extends React.Component { 

    showRight: function() { 
    this.refs.right.show(); 
    } 

    render() { 
    return (
     <div> 
     <button onClick={this.showRight}>Show Left Menu!</button> 
     {/* 
     <Menu ref="right" alignment="right"> 
      <MenuItem hash="1">First</MenuItem> 
      <MenuItem hash="2">Second</MenuItem> 
      <MenuItem hash="3">Third</MenuItem> 
     </Menu> 
     */} 
     </div> 
    ); 
    } 
} 

以下是錯誤:

./src/components/ToggleMenu/ ToggleMenu.js Module build failed: SyntaxError: Unexpected token (13:14)

showRight: function() { 
    this.refs.right.show(); 
} 

回答

1

你越來越對象文字和類混合起來。您的代碼位於類中,而不是對象文字,因此您必須像使用render一樣使用方法定義語法。類只能包含原型方法和構造函數(如ECMAScript的2015年):

showRight() { 
    this.refs.right.show(); 
} 

否則會被解釋爲label和函數聲明,但與function關鍵字函數的聲明不能在類主體從而語法錯誤:

showRight: //label 
function() { //function declaration, not valid in class body! 
    ... 
} 

此外,確保bind(this)你的方法,使this指的是組件,而不是全球範圍內的this值:

constructor(props) { 
    super(props); 
    this.showRight = this.showRight.bind(this); 
} 

閱讀MDN更多關於class bodies


關於你的ref的使用,你應該使用一個回調,而不是一個簡單的字符串:

<Menu ref={right => this.right = right} alignment="right"> 

然後在您的showRight

this.right.hide(); 
+0

確定有意義感謝ü但至少爲何IM歌廳下一個錯誤:未捕獲的(以諾)類型錯誤:無法讀取未定義 – Alex

+0

@Alex的特性「綁定」你確定你把它在構造函數? – Li357

+0

'出口默認類ToggleMenu擴展React.Component { 構造(道具){ 超(道具); this.showRight = this.showRight.bind(this); } 渲染(){ 回報(

{/* this.right = right} alignment="right"> First Second Third */}
); } }'是我確定.. u能告訴我什麼是錯 – Alex