❗常犯錯誤,需要特別注意的
class
在HTML中用來指定元素的CSS類別,但在JSX中應使用className
。
<div class="my-class"></div>
<div className="myClass"></div>
for
在HTML中用在<label>
元素,連結到表單元素的 id,但在JSX中應使用htmlFor
。
<label for="my-input"></label>
<label htmlFor="myInput"></label>
tabIndex
,readOnly
**等。<input>
、<br>
**等可以不用閉合標籤,但在 JSX 中必須自閉合。
<input type="text">、<br>
<input type="text" />、<br />
<div style="color: red; font-size: 16px;"></div>
<div style={{color: "red", fontSize: "16px"}}></div>
{}
來插入 JavaScript 表達式。
<h1>{ "Hello " + name }</h1>
<!-- -->
作為注釋,但在JSX中要使用 {/* */}
作為注釋。disabled
,只要它出現,就表示 disabled=true
。
<input type="text" disabled>
true
或 false
來指定布林屬性。
<input type="text" disabled={true} />
或 <input type="text" disabled={false} />
<ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul>
onclick="myFunction()"
。<button onClick={myFunction}>Click me</button>
在一個 JSX 表達式中,如果你有多個元素,他們必須被包裹在一個元素裡面。如果在 HTML 中,我們可以有多個沒有被包裹的兄弟元素。
<div>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</div>
<></>
來替代<>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</>