React-TS-Form 使用教程
react-ts-form项目地址:https://gitcode.com/gh_mirrors/re/react-ts-form
1. 项目介绍
react-ts-form
是一个用于构建可维护、类型安全的表单的工具库。它通过结合 zod
和 react-hook-form
,帮助开发者减少构建表单时的样板代码,同时不牺牲自定义性。
主要特性
- 自动生成类型安全表单:使用
zod
模式自动生成类型安全的表单。 - 消除重复的 JSX:通过类型安全的属性传递,减少表单组件的重复代码。
- 完全控制组件:通过类型安全的属性,完全控制表单组件的渲染。
- 无头 UI:可以渲染任何 React 组件。
- 提升生产力:提供一些在原生
zod
和react-hook-form
中难以实现的质量和生产力特性。 - 轻量级:库本身非常小,压缩后仅约 3KB。
- 良好的测试覆盖:确保库的稳定性和可靠性。
2. 项目快速启动
安装
确保你的 tsconfig.json
中设置了 "strict": true
,并且编辑器的 TypeScript 版本设置为 v4.9 或更高版本(以确保更好的智能感知)。
使用你喜欢的包管理器安装 react-ts-form
及其依赖:
yarn add @ts-react/form # 必需的 peer dependencies
yarn add zod react-hook-form @hookform/resolvers
使用
- 创建 Zod 到组件的映射:
import { createTsForm } from '@ts-react/form';
import { z } from 'zod';
// 创建 Zod 模式到组件的映射
const mapping = [
[z.string(), TextField],
[z.boolean(), CheckboxField],
// 添加更多映射
] as const;
// 创建表单
const MyForm = createTsForm(mapping);
- 定义表单模式:
const schema = z.object({
name: z.string().min(1, 'Name is required'),
email: z.string().email('Invalid email'),
agree: z.boolean().refine(val => val, 'You must agree to the terms'),
});
- 渲染表单:
function App() {
return (
<MyForm
schema={schema}
onSubmit={(data) => {
console.log(data);
}}
renderAfter={() => <button type="submit">Submit</button>}
props={{
email: { className: "mt-2" }
}}
/>
);
}
3. 应用案例和最佳实践
应用案例
假设你正在开发一个用户注册表单,你可以使用 react-ts-form
来快速构建一个类型安全的表单。以下是一个简单的示例:
import { createTsForm } from '@ts-react/form';
import { z } from 'zod';
const schema = z.object({
name: z.string().min(1, 'Name is required'),
email: z.string().email('Invalid email'),
password: z.string().min(8, 'Password must be at least 8 characters'),
agree: z.boolean().refine(val => val, 'You must agree to the terms'),
});
const mapping = [
[z.string(), TextField],
[z.boolean(), CheckboxField],
] as const;
const MyForm = createTsForm(mapping);
function RegistrationForm() {
return (
<MyForm
schema={schema}
onSubmit={(data) => {
console.log(data);
}}
renderAfter={() => <button type="submit">Register</button>}
props={{
email: { className: "mt-2" }
}}
/>
);
}
最佳实践
- 自定义表单组件:建议创建自定义表单组件来处理重复的代码,例如提交按钮的渲染。
- 使用严格的 TypeScript 配置:确保
tsconfig.json
中设置了"strict": true
,以获得最佳的类型检查和智能感知。 - 保持模式简洁:尽量保持
zod
模式的简洁和清晰,避免过于复杂的嵌套结构。
4. 典型生态项目
react-ts-form
通常与其他一些流行的 React 生态项目一起使用,以构建更复杂的应用。以下是一些典型的生态项目:
- Zod:用于定义表单模式的类型安全验证库。
- React Hook Form:用于管理表单状态和验证的库。
- Tailwind CSS:用于样式化的实用程序优先 CSS 框架。
- React Router:用于管理应用路由的库。
这些工具的结合使用,可以帮助你构建出功能强大且易于维护的 React 应用。
react-ts-form项目地址:https://gitcode.com/gh_mirrors/re/react-ts-form