这个问题
解析错误:相邻的JSX元素必须封装在一个封闭标记中
这意味着您试图以不正确的方式返回多个同级JSX元素。请记住,您不是在编写HTML,而是JSX!您的代码将从JSX转换为JavaScript。例如:
render() {
return (<p>foo bar</p>);
}
将转化为:
render() {
return React.createElement("p", null, "foo bar");
}
除非您是编程新手,否则您已经知道(任何语言的)函数/方法可以接受任意数量的参数,但总是只返回一个值。鉴于此,您可能会发现,根据createElement()的工作方式试图返回多个兄弟组件时会出现问题;它只接受一个元素的参数并返回。因此,一次函数调用不能返回多个元素。
所以如果你想知道为什么这样做…
render() {
return (
<div>
<p>foo</p>
<p>bar</p>
<p>baz</p>
</div>
);
}
但不是这个……
render() {
return (
<p>foo</p>
<p>bar</p>
<p>baz</p>
);
}
这是因为在第一个代码片段中,<p>-元素都是<div>-元素的子元素的一部分。当它们是子元素的一部分时,我们可以表达无限数量的兄弟元素。看看这句话是怎么说的:
render() {
return React.createElement(
"div",
null,
React.createElement("p", null, "foo"),
React.createElement("p", null, "bar"),
React.createElement("p", null, "baz"),
);
}
解决方案
取决于你正在运行的React版本,你确实有几个选项来解决这个问题:
Use fragments (React v16.2+ only!)
As of React v16.2, React has support for Fragments which is a node-less component that returns its children directly.
Returning the children in an array (see below) has some drawbacks:
Children in an array must be separated by commas.
Children in an array must have a key to prevent React’s key warning.
Strings must be wrapped in quotes.
These are eliminated from the use of fragments. Here's an example of children wrapped in a fragment:
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
);
}
which de-sugars into:
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
Note that the first snippet requires Babel v7.0 or above.
Return an array (React v16.0+ only!)
As of React v16, React Components can return arrays. This is unlike earlier versions of React where you were forced to wrap all sibling components in a parent component.
In other words, you can now do:
render() {
return [<p key={0}>foo</p>, <p key={1}>bar</p>];
}
this transpiles into:
return [React.createElement("p", {key: 0}, "foo"), React.createElement("p", {key: 1}, "bar")];
Note that the above returns an array. Arrays are valid React Elements since React version 16 and later. For earlier versions of React, arrays are not valid return objects!
Also note that the following is invalid (you must return an array):
render() {
return (<p>foo</p> <p>bar</p>);
}
Wrap the elements in a parent element
The other solution involves creating a parent component which wraps the sibling components in its children. This is by far the most common way to address this issue, and works in all versions of React.
render() {
return (
<div>
<h1>foo</h1>
<h2>bar</h2>
</div>
);
}
Note: Take a look again at the top of this answer for more details and how this transpiles.