简体   繁体   English

return语句中react render()函数内部的意外令牌,预期为“,”

[英]unexpected token, expected “,” inside of react render() function in the return statement

The error is unexpected token, expected "," in the render return function. 错误是渲染返回函数中的意外令牌,应为“,”。 I am using babel and linking this file in an html file. 我正在使用babel并将此文件链接为html文件。 I removed the comment class and component for viewing purposes. 我删除了注释类和组件以进行查看。 Also I removed the comment form component. 我也删除了评论表单组件。

Here is main.js: 这是main.js:

class App extends React.Component {
    constructor(props) {
        super(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.state = { comments : [] }
    }
    handleSubmit(event) {
        // ...
    }
    render() {
        const comments = this.state.comments.map((comment) => {
            <Comment author={comment.author} message={comment.message} />
        });
        const formcomment = <CommentForm handleSubmit = {this.handleSubmit} />;
        return (
            {comments}
            {formcomment} // ERROR HERE
        )
    }
}

ReactDOM.render(<App />, document.getElementById("root"))

The problem occurs, because JSX requires you to only have one root element. 发生问题是因为JSX只需要一个根元素。 In your case you're having two root elements. 就您而言,您有两个根元素。

If you want to return multiple elements, you need to wrap them into some sort of container, most of the time a simple div will be sufficient: 如果要返回多个元素,则需要将它们包装到某种容器中,大多数情况下,一个简单的div就足够了:

return (
  <div>
    {comments}
    {formcomment}
  </div>
);

If the div is disrupting your styling, you might want to use a Fragment instead. 如果div破坏了样式,则可能需要使用Fragment

Read more about JSX in general here and here . 此处此处 ,全面了解有关JSX的更多信息。

EDIT: 编辑:

As Emile Bergeron pointed out, you can also return an array as of React 16.2: 正如Emile Bergeron指出的那样,您还可以从React 16.2开始返回一个数组:

render() {
  return [comments, formcomment];
}

Reference . 参考

The problem is that you are trying to render multiple elements without a parent container. 问题是您试图在没有父容器的情况下渲染多个元素。

You should be able to fix this by adding <Fragment> ... </Fragment> (or, more simply, <> ... </> ) around the contents of your return statement. 您应该能够通过在return语句的内容周围添加<Fragment> ... </Fragment> (或更简单地说, <> ... </> )来解决此问题。 This will give the JSX transpiler a single element to render with. 这将为JSX编译器提供一个要渲染的元素。

The usual fix for this is using a "wrapper div", but using a Fragment like this is the new way of wrapping elements without adding nodes to the DOM. 通常的解决方法是使用“包装器div”,但使用Fragment这样的新方法是在不向DOM添加节点的情况下包装元素的新方法。

Checkout out this page to learn more about this problem and React fragments. 签出此页面以了解有关此问题和React片段的更多信息。

您是否尝试过将返回值包装在div或fragment( <></> )中?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM