0

我的代码中有语法错误,我不知道为什么。这与我使用 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模块构建失败:SyntaxError: Unexpected token (13:14)

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

1 回答 1

1

您将对象文字和类混淆了。您的代码在类中,而不是对象文字中,因此您必须使用方法定义语法,就像使用render. 类只能包含原型方法和构造函数(从 ECMAScript 2015 开始):

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

否则它将被解释为标签和函数声明,但带有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 上阅读更多关于班级机构的信息。


关于您对refs 的使用,您应该使用回调而不是纯字符串:

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

然后在你的showRight

this.right.hide();
于 2017-06-02T16:08:18.137 回答