Label 标签
渲染与表单控件关联的无障碍标签。
用法
import { Label } from '@lenso/ui';此预览复用英文版适配,不代表中文源示例已完成本地实现。
"use client";// Adapted from HeroUI v3.2.6, Apache-2.0.import { Input, Label } from "@lenso/ui";import * as stylex from "@stylexjs/stylex";import { useId } from "react";import { demoStyles } from "../../demo.stylex";
export function Basic() { const id = useId(); return ( <div {...stylex.props(demoStyles.column)}> <Label htmlFor={id}>Name</Label> <Input xstyle={demoStyles.field} id={id} placeholder="Enter your name" type="text" /> </div> );}Local adaptation source above. Derived from HeroUI v3.2.6 source.
示例
带必填指示符
<Label htmlFor="email" isRequired> Email Address</Label><Input id="email" type="email" />禁用状态
<Label htmlFor="username" isDisabled> Username</Label><Input id="username" isDisabled />无效状态
<Label htmlFor="password" isInvalid> Password</Label><Input id="password" isInvalid />自定义样式
Tailwind CSS
此预览复用英文版适配,不代表中文源示例已完成本地实现。
"use client";// Adapted from HeroUI v3.2.6, e385ac202b2cdb94b1bf6fa76d32c31c8259cc5e, Apache-2.0.import { Input, Label } from "@lenso/ui";import * as stylex from "@stylexjs/stylex";import { useId } from "react";
const styles = stylex.create({ layout: { display: "flex", flexDirection: "column", gap: 6 }, label: { fontSize: 12, fontWeight: 600, letterSpacing: "0.025em", color: "var(--accent)", textTransform: "uppercase", }, input: { width: 256, maxWidth: "100%", backgroundColor: "var(--field-background)" },});
export function CustomStyles() { const id = useId(); return ( <div {...stylex.props(styles.layout)}> <Label xstyle={styles.label} htmlFor={id}> Repository </Label> <Input xstyle={styles.input} id={id} placeholder="heroui/react" /> </div> );}Local adaptation source above. Derived from HeroUI v3.2.6 source.
全局 CSS
若要自定义组件类,可使用 @layer components 指令。了解更多。
@layer components { .label { @apply font-semibold text-foreground; }
.label--required::after { @apply text-accent; }}样式参考
HeroUI 遵循 BEM 方法论,确保组件变体与状态可复用且易于自定义。
CSS 类
Label 使用以下 CSS 类(查看源码样式):
基础类 [!toc]
.label— 基础标签文本样式
状态修饰类 [!toc]
.label--required或[data-required="true"] > .label— 显示必填星号.label--disabled或[data-disabled="true"] .label— 禁用状态样式.label--invalid或[data-invalid="true"] .label或[aria-invalid="true"] .label— 无效状态样式(危险/红色文本)
说明: 必填星号会基于 role 与 data-slot 智能应用,并排除:
role="group"、role="radiogroup"、role="checkboxgroup"的元素data-slot="radio"或data-slot="checkbox"的元素
从而在分组组件与必填字段组合时避免重复星号。
API 参考
Label
| Prop | 类型 | 默认值 | 描述 |
|---|---|---|---|
htmlFor | string | - | 标签所关联元素的 id |
isRequired | boolean | false | 是否显示必填指示符 |
isDisabled | boolean | false | 标签是否处于禁用状态 |
isInvalid | boolean | false | 标签是否处于无效状态 |
className | string | - | 附加的 CSS 类 |
children | ReactNode | - | 标签内容 |
无障碍
Label 基于原生 HTML <label>(MDN 参考),并遵循 WAI-ARIA 最佳实践:
- 使用
htmlFor与表单控件关联 - 提供语义化的
<label>元素 - 与表单控件关联时支持键盘导航
- 向屏幕阅读器传达必填与无效状态
- 点击标签可聚焦/激活关联的表单控件