React
表单标签与 htmlFor 属性
在 React 中必须使用 htmlFor 而不是 HTML 的 for 属性,因为 for 是 JavaScript 的保留字,会导致语法错误。
一、属性命名转换
React 中的 JSX 属性遵循 camelCase 约定,HTML 属性在转换时需要做如下转换:
| HTML 属性 | React 属性 | 原因 |
|---|---|---|
class | className | 避免与 JS 关键字冲突 |
for | htmlFor | 避免与 for 循环冲突 |
tabindex | tabIndex | camelCase 约定 |
readonly | readOnly | camelCase 约定 |
二、正确使用方式
✓ 显式关联:使用 htmlFor + id
function LoginForm() {
return (
<form>
<label htmlFor="username">用户名:</label>
<input id="username" type="text" />
<label htmlFor="password">密码:</label>
<input id="password" type="password" />
</form>
)
}点击 label 时,浏览器会自动聚焦关联的 input。
✗ 错误写法
// 这会产生语法错误,for 是保留字
<label for="username">用户名:</label>三、label 的两种关联方式
方式一:显式关联(推荐)
使用 htmlFor 和 id 属性建立关联,适合复杂表单。
function CheckboxField() {
return (
<div>
<label htmlFor="agree">
<input id="agree" type="checkbox" />
我同意服务条款
</label>
</div>
)
}方式二:隐式关联
将 input 直接嵌套在 label 中,关联自动建立。
function TextField() {
return (
<label>
用户名:
<input type="text" />
</label>
)
}四、使用 useId 生成唯一 ID
当需要在组件多次使用时,useId Hook 确保每个实例的 ID 都是唯一的,避免 ID 冲突。
import { useId } from 'react'
function FormField({ label, type }: { label: string; type: string }) {
const id = useId()
return (
<div>
<label htmlFor={id}>{label}:</label>
<input id={id} type={type} />
</div>
)
}
function Form() {
return (
<>
<FormField label="姓名" type="text" />
<FormField label="邮箱" type="email" />
</>
)
}一句话记住:
for是 JavaScript 保留字,React 中用htmlFor替代,这样既避免了语法冲突,也符合 camelCase 命名约定。