Unexpected token when rendering React component

时光怂恿深爱的人放手 提交于 2020-01-10 04:45:25

问题


This is a snippet of my component code:

renderEditor() {
    return (
      <FroalaEditor 
       base='https://cdnjs.cloudflare.com/ajax/libs/froala-editor/2.3.4'
       value={this.state.value} 
      />
    );    
}

render() {
    return (
      {this.renderEditor()}
    );
}

But when I run this code I get an unexpected token error at {this.renderEditor()}. Why does this happen and how can I fix it?


回答1:


You have to wrap your method invocation in a JSX element or else Babel won't recognize the return statement as JSX, or an inline JSX expression in this case. It won't transpile your code from JSX to plain JavaScript, hence the error. It actually is interpreted as an object literal, not an inline JSX expression as you expect:

return (
    {this.renderEditor()} //interpreted as an object literal, `return ({ ... })`
    //   ^ The . here is an unexpected token in an object literal hence the error
);

The solution is to wrap it in an element to tell Babel it's JSX, so it is transpiled and the {} are interpreted correctly.

return (
    <div>
        {this.renderEditor()}
    </div>
);

This will make the return value of the method a child of the <div> and won't be interpreted as an object literal. And if you're only returning just the method invocation without any other siblings, you can just remove the () grouping and <div>s altogether:

return this.renderEditor();

This will prevent the code from being interpreted as an object literal in the first place, and will return the return value of he method, which is the component.


This also applies to other situations such as:

return (
  {foo}
);

It's interpreted as an object because () is the grouping operator, and can only contain expressions. An object literal is an expression, thus an object literal with shorthand properties is returned. It desugars and transpiles to:

return {
  foo: foo
};

Which is not a valid React element or null, thus the error occurs. In this case though, if foo is not a valid React element, you have to wrap it in a valid React element -- you can't just do return foo. If foo were an array, you'd have to wrap it in something such as a <div> because render must return a React element or null, which an array is neither.



来源:https://stackoverflow.com/questions/43691502/unexpected-token-when-rendering-react-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!