const Article = () => (
<h3>This is title</h3>
<p>This is content</p>
<span>This is author</span>
);
上述代码在编译的时候会产生如下错误:
"Parsing error: Adjacent JSX elements must be wrapped in a closing tag。"
1、正确的做法有如下几种方式:
正确的做法是用一个元素把以上内容都包裹起来,通常用<div></div>。
const Article = () => (
<div>
<h3>This is title</h3>
<p>This is content</p>
<span>This is author</span>
</div>
);
用<div></div>标签包裹元素会导致渲染出的DOM树中多出一层div节点,尽管大多数时候这样做影响不大,但当需要渲染精确的DOM结构时就会出现问题。此时可以使用React.Fragment包裹组件元素,写法如下:
const Article = () => (
<React.Fragment>
<h3>This is title</h3>
<p>This is content</p>
<span>This is author</span>
</React.Fragment>
);
或者
const Article = () => (
<>
<h3>This is title</h3>
<p>This is content</p>
<span>This is author</span>06
</>
);
所有的标签一定要闭合,例如,<span>hello</span>。即使在HTML中通常不闭合的标签,如<img>,也应该写成自闭合的形式,如<img />。如果在编译代码时提示“Expected corresponding JSX closing tag for...”,则需要检查代码中是否有未闭合的标签。