【问题标题】:Why is there a syntax error in my React component class?为什么我的 React 组件类中有语法错误?
【发布时间】:2017-06-02 16:04:15
【问题描述】:

我的代码中有语法错误,我不知道为什么。和我使用 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();  
}

【问题讨论】:

    标签: reactjs ecmascript-6 es6-class refs


    【解决方案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 的更多信息。


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

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

    然后在你的showRight:

    this.right.hide();
    

    【讨论】:

    • 好吧,谢谢你,但至少为什么我得到下一个错误:未捕获(承诺)类型错误:无法读取未定义的属性“绑定”
    • @Alex 你确定你把它放在构造函数中了吗?
    • export default class ToggleMenu extends React.Component { constructor(props) { super(props); this.showRight = this.showRight.bind(this); } render() { return ( &lt;div&gt; &lt;button onClick={this.showRight}&gt;Show Left Menu!&lt;/button&gt; {/* &lt;Menu ref={right =&gt; this.right = right} alignment="right"&gt; &lt;MenuItem hash="1"&gt;First&lt;/MenuItem&gt; &lt;MenuItem hash="2"&gt;Second&lt;/MenuItem&gt; &lt;MenuItem hash="3"&gt;Third&lt;/MenuItem&gt; &lt;/Menu&gt; */} &lt;/div&gt; ); } } 是的,我确定.. 你能告诉我有什么问题吗
    • 好吧,您的示例中没有 showRight 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    相关资源
    最近更新 更多