为什么我的 React 组件中存在语法错误 class?

Why is there a syntax error in my React component class?

我的代码中有一个语法错误,我不确定为什么。跟我使用refs的方式有关系吗?

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();  
}

您将对象文字和 classes 混淆了。您的代码位于 class 中,而不是对象文字,因此您必须像使用 render 一样使用方法定义语法。 类 只能包含原型方法和构造函数(自 ECMAScript 2015 起):

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

否则它将被解释为 label 和函数声明,但是带有 function 关键字的函数声明不能​​在 class 主体中因此语法错误:

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();