Javascript React — 语法错误:Unexpected token, expected ;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45279552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:59:15  来源:igfitidea点击:

React — Syntax error: Unexpected token, expected ;

javascriptreactjssyntax-errorcomponents

提问by Diego Oriani

For some reason that I can't figure it out I am getting a syntax error in the following React component. The error is in the first curly bracketon the renderItem(). What's wrong?

出于某种原因,我无法弄清楚我在以下 React 组件中遇到了语法错误。该错误是在第一个curly bracketrenderItem()。怎么了?

Thank you in advance.

先感谢您。

import _ from 'lodash';
import React from 'react';
import { ToDoListHeader } from './todo-list-header';
import { ToDoListItem } from './todo-list-item';

export const ToDoList = (props) => {
  renderItems() {
    return _.map(this.props.todos, (todo, index) => <ToDoListItem key={index} {...todo} />)
  }

  return (
    <div>
      <table>
        <ToDoListHeader />
        <tbody>
          {/* {this.renderItems()} */}
        </tbody>
      </table>
    </div>
  );
}

回答by kind user

Well, you are getting error because you are defining the function like in a class, not in a function. Use a proper function declaration.

好吧,您之所以会出错,是因为您像在类中而不是在函数中一样定义函数。使用正确的函数声明。

export const ToDoList = (props) => {
  const renderItems = () => {
    return _.map(this.props.todos, (todo, index) => <ToDoListItem key={index} {...todo} />)
  }

  return (
    <div>
      <table>
        <ToDoListHeader />
        <tbody>
          {/* {this.renderItems()} */}
        </tbody>
      </table>
    </div>
  );
}

It would work fine, if only ToDoListwas a class, though.

ToDoList不过,如果只是一个类,它会工作得很好。

回答by Andrew

  renderItems = () => {
    return _.map(this.props.todos, (todo, index) => <ToDoListItem key={index} {...todo} />)
  }

Your varian will work with es6 classes.

您的 varian 将与 es6 类一起使用。