React Jsonschema Form使用小记
最近老大让我看一下能不能用JSON生成表单,这样每次开发就不用发版了,直接在远程配置JSON就可以生成一个新的表单了。
大约搜索了一下,找到了基于React的 react-jsonschema-form
方案。
安装
1npm install @rjsf/core --save
在项目中引入
1import Form from "@rjsf/core";
Demo
1import Form from "@rjsf/core";
2
3
4const schema = {
5 title: "Test form",
6 type: "object",
7 properties: {
8 name: {
9 type: "string"
10 },
11 age: {
12 type: "number"
13 }
14 }
15};
16
17const uiSchema = {
18 name: {
19 classNames: "custom-class-name"
20 },
21 age: {
22 classNames: "custom-class-age"
23 }
24}
25
26
27const log = (type) => {console.log(type)}
28
29function MyForm() {
30 return (
31 <Form
32 schema={schema}
33 uiSchema={uiSchema}
34 onChange={(e) => console.log('change', e)}
35 onSubmit={log.bind(this, 'submit')}
36 onError={log("errors")}
37 />
38 );
39}
40
41export default MyForm;
42
效果:
高级用法总结
- 支持5种基础数据类型
- string
- number
- integer
- boolean
- null
- 支持Object、Array组合数据类型。
- 支持数据验证
- 支持插件
- 支持主题
未完待续
如何从服务端动态获取数据?