![](/img/trans.png)
[英]Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag
[英]I keep getting Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag
這是代碼
import React from 'react';
function Home() {
return (
<div className="home">
<h1>This is my home page!</h1>
</div>
<h2>Welcome and take a look around</h2>
</div>
);
}
export default Home;
這是錯誤
./src/components/home.js Line 9:7: Parsing error: Adjacent JSX
elements must be wrapped in an enclosing tag. Did you want a JSX
fragment <>...</>?
7 | <h1>This is my home page!</h1>
8 | </div>
9 | <h2>Welcome and take a look around</h2>
| ^
10 | </div>
除了您的 html 在上面的示例中由於 2 個關閉 div 標簽而無效之外,包裝 React 代碼塊而無需添加不必要的 div 的最簡單方法是使用 React.Fragment:
import React, { Fragment } from 'react
...
return (
<Fragment>
<h1>A heading</h1>
<p>A paragraph</p>
</Fragment>
)
然而,有一個更簡單的方法,你會喜歡或討厭,它是使用 Fragment 的速記並且不需要特殊的導入:
<>
<h1>A heading</h1>
<p>A paragraph</p>
</>
就個人而言,這是我的首選方法,但我可以理解,如果您的應用程序有多個不習慣這種語法的維護者,可能會更難閱讀。
起初,您沒有使用第二個 div 部分(第 9 行)。 此外,您應該將所有元素放在一個部分中,例如,,等。
import React from 'react';
function Home() {
return (
<React.fragment className="home">
<h1>This is my home page!</h1>
<h2>Welcome and take a look around</h2>
</React.fragment>
);
}
export default Home;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.