Formily 开源项目教程
项目介绍
Formily 是一个跨设备、高性能的表单解决方案,支持 React、React Native、Vue 2 和 Vue 3。它提供了普通表单、动态(JSON Schema)表单以及表单构建器,旨在通过独立管理字段来实现高性能的表单渲染。Formily 集成了阿里巴巴的 Fusion 和 Ant Design 组件,确保开箱即用,并且支持后端 JSON Schema 和前端 JSchema 的转换。
项目快速启动
安装
首先,你需要通过 npm 或 yarn 安装 Formily:
npm install @formily/core @formily/react
或者
yarn add @formily/core @formily/react
创建一个简单的表单
以下是一个使用 Formily 创建简单表单的示例:
import React from 'react';
import { createForm } from '@formily/core';
import { FormProvider, Field } from '@formily/react';
import { Input, Form, Button } from 'antd';
const form = createForm();
const SimpleForm = () => {
return (
<FormProvider form={form}>
<Form layout="vertical">
<Field
name="username"
title="用户名"
initialValue="hello world"
decorator={[Form.Item]}
component={[Input]}
/>
<Field
name="password"
title="密码"
decorator={[Form.Item]}
component={[Input.Password]}
/>
<Button type="primary" onClick={() => form.submit()}>
提交
</Button>
</Form>
</FormProvider>
);
};
export default SimpleForm;
应用案例和最佳实践
动态表单
Formily 支持动态表单,可以通过 JSON Schema 来定义表单结构。以下是一个动态表单的示例:
import React from 'react';
import { createForm } from '@formily/core';
import { FormProvider, createSchemaField } from '@formily/react';
import { Input, Form, Button } from 'antd';
const form = createForm();
const SchemaField = createSchemaField({
components: {
Input,
},
});
const schema = {
type: 'object',
properties: {
username: {
type: 'string',
title: '用户名',
'x-decorator': 'FormItem',
'x-component': 'Input',
},
password: {
type: 'string',
title: '密码',
'x-decorator': 'FormItem',
'x-component': 'Input.Password',
},
},
};
const DynamicForm = () => {
return (
<FormProvider form={form}>
<Form layout="vertical">
<SchemaField schema={schema} />
<Button type="primary" onClick={() => form.submit()}>
提交
</Button>
</Form>
</FormProvider>
);
};
export default DynamicForm;
表单验证
Formily 提供了强大的表单验证功能,可以通过 schema 定义验证规则:
const schema = {
type: 'object',
properties: {
username: {
type: 'string',
title: '用户名',
'x-decorator': 'FormItem',
'x-component': 'Input',
'x-validator': {
required: true,
message: '用户名不能为空',
},
},
password: {
type: 'string',
title: '密码',
'x-decorator': 'FormItem',
'x-component': 'Input.Password',
'x-validator': {
required: true,
message: '密码不能为空',
},
},
},
};
典型生态项目
Form Builder
Form Builder 是 Formily 的一个生态项目,它允许你通过可视化界面快速构建表单。你可以访问 Form Builder 网站 了解更多信息。