组件目录

Form表单

组合文本、密码、选择器、复选框和开关,提供字段校验、保存与取消。

npx https://kalos-ui-six.vercel.app/cli/kalos-ui-0.3.12.tgz add form
MCP
成员设置
至少 8 位

安装

在项目根目录运行,安装源码。

npx https://kalos-ui-six.vercel.app/cli/kalos-ui-0.3.12.tgz add form

使用

React
"use client";
import { KalosForm, type KalosFormField, type KalosFormValues } from "@/components/ui/kalos-form";
const fields: KalosFormField[] = [  { name: "email", label: "邮箱地址", type: "email", required: true, autoComplete: "email" },  { name: "password", label: "密码", type: "password", required: true, placeholder: "请输入密码", minLength: 8, hint: "至少 8 位", autoComplete: "new-password" },  { name: "role", label: "成员角色", type: "select", required: true, items: [{ value: "editor", label: "编辑者" }, { value: "viewer", label: "查看者" }] },  { name: "notifications", label: "消息通知", type: "switch" },  { name: "terms", label: "同意服务条款", type: "checkbox", required: true },];
export default function Example() {  async function save(values: KalosFormValues) {    // 替换为你的保存接口;失败时抛出异常,表单会保留输入并显示重试提示。    const response = await fetch("/api/members", {      method: "POST",      headers: { "Content-Type": "application/json" },      body: JSON.stringify(values),    });    if (!response.ok) throw new Error("保存失败");  }
  return <KalosForm title="成员设置" fields={fields} defaultValues={{ notifications: true }} onSubmit={save} aria-label="成员设置" />;}

API

属性类型默认值说明
titlestring表单卡片标题
fieldsKalosFormField[]—字段列表;每项的 name 唯一,支持 text、email、password、select、checkbox、switch
fields[].requiredbooleanfalse输入与选择项显示红色 *,复选框不显示;格式随输入实时校验,必填空值在保存或已填内容清空时校验
fields[].minLengthnumber—文本与密码的最少字符数;密码不去除空格
fields[].hintstring—输入约束;校验错误出现时替代此提示
fields[].items{ value: string; label: string }[]—select 的候选项
fields[].placeholder / autoComplete / disabledstring / string / boolean—输入占位、自动填充与字段禁用状态
defaultValuesRecord<string, string | boolean>{}挂载时的初始值;后续更换数据时通过 key 重新挂载
validate(values: KalosFormValues) => Record<string, string>—同步自定义校验,按字段名返回错误;叠加在内置必填、邮箱、选项与长度校验上
onSubmit(values: KalosFormValues) => void | Promise<void>—点击保存校验全部字段后调用;等待保存时禁用控件,异常时保留输入并显示错误
onCancel() => void—恢复到初始值或最近一次保存成功的值,并清除错误
submitLabel / cancelLabelstring保存 / 取消操作按钮文本
disabledbooleanfalse禁用整个表单

键盘操作

Tab / Shift + Tab
按顺序移动到字段、密码显示按钮与操作按钮
Enter
在文本输入中提交,校验失败时聚焦首个错误字段
Space
切换复选框、开关,或激活当前按钮
↑ / ↓ / Esc
在选择器内移动选项或关闭列表