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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…