2017-06-02 72 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