Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

javascript - Unexpected token when rendering React component

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...