最近在用ant design做后臺(tái)管理系統(tǒng),表單真是蛋疼的存在蘑拯。
下面貼一段截自與ant design官網(wǎng)的代碼
import { Form, Icon, Input, Button } from 'antd';
const FormItem = Form.Item;
function hasErrors(fieldsError) {
return Object.keys(fieldsError).some(field => fieldsError[field]);
}
class HorizontalLoginForm extends React.Component {
componentDidMount() {
// To disabled submit button at the beginning.
this.props.form.validateFields();
}
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
}
render() {
const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
// Only show error after a field is touched.
const userNameError = isFieldTouched('userName') && getFieldError('userName');
const passwordError = isFieldTouched('password') && getFieldError('password');
return (
<Form layout="inline" onSubmit={this.handleSubmit}>
<FormItem
validateStatus={userNameError ? 'error' : ''}
help={userNameError || ''}
>
{getFieldDecorator('userName', {
rules: [{ required: true, message: 'Please input your username!' }],
})(
<Input prefix={<Icon type="user" style={{ fontSize: 13 }} />} placeholder="Username" />
)}
</FormItem>
<FormItem
validateStatus={passwordError ? 'error' : ''}
help={passwordError || ''}
>
{getFieldDecorator('password', {
rules: [{ required: true, message: 'Please input your Password!' }],
})(
<Input prefix={<Icon type="lock" style={{ fontSize: 13 }} />} type="password" placeholder="Password" />
)}
</FormItem>
<FormItem>
<Button
type="primary"
htmlType="submit"
disabled={hasErrors(getFieldsError())}
>
Log in
</Button>
</FormItem>
</Form>
);
}
}
const WrappedHorizontalLoginForm = Form.create()(HorizontalLoginForm);
ReactDOM.render(<WrappedHorizontalLoginForm />, mountNode);
代碼看的是真心累,各種方法屬性以及html混合在一起,第一眼就不想看了盛霎。
思考:有沒有方便簡(jiǎn)單的方式來定義一個(gè)表單,像下面這樣的:
{
"userName":{
required:true,
type:"string",
message:{
required:"Please input your username!"
}
},
"password":{
required:true,
type:"string",
message:{
required:"Please input your Password!"
}
}
}
在公共代碼庫中找了下耽装,還真有類似的類庫愤炸, react-jsonschema-form;這個(gè)庫只需要提供2份配置即可生成出界面掉奄,一份是json schema规个,一份是ui schema。真是便利的表單,配置即代碼诞仓。
下面來看下簡(jiǎn)單的配置:
{
"title": "A registration form",
"description": "A simple form example.",
"type": "object",
"required": [
"firstName",
"lastName"
],
"properties": {
"firstName": {
"type": "string",
"title": "First name"
},
"lastName": {
"type": "string",
"title": "Last name"
},
"age": {
"type": "integer",
"title": "Age"
},
"bio": {
"type": "string",
"title": "Bio"
},
"password": {
"type": "string",
"title": "Password",
"minLength": 3
},
"telephone": {
"type": "string",
"title": "Telephone",
"minLength": 10
}
}
}
{
"firstName": {
"ui:autofocus": true,
"ui:emptyValue": ""
},
"age": {
"ui:widget": "updown",
"ui:title": "Age of person",
"ui:description": "(earthian year)"
},
"bio": {
"ui:widget": "textarea"
},
"password": {
"ui:widget": "password",
"ui:help": "Hint: Make it strong!"
},
"date": {
"ui:widget": "alt-datetime"
},
"telephone": {
"ui:options": {
"inputType": "tel"
}
}
}
json schema可以放在公共服務(wù)器热鞍,后端也可以使用同樣的json schema來驗(yàn)證數(shù)據(jù)的合法性疗琉,同樣的驗(yàn)證方式镇防,同樣的錯(cuò)誤消息股囊,真實(shí)簡(jiǎn)單實(shí)用。
但是很快問題就來了:
- 當(dāng)表單的布局很復(fù)雜的時(shí)候怎么辦谍婉;比如firstName和lastName一行舒憾,使用一個(gè)fieldSet來包裹,其他使用默認(rèn)的配置生成表單穗熬。
- 當(dāng)需要擴(kuò)展功能的時(shí)候珍剑,比如我需要一個(gè)顯示/隱藏的功能;當(dāng)firstName和lastName都填寫之后才顯示其他字段等等死陆。
- 當(dāng)我一些動(dòng)態(tài)數(shù)據(jù)的需求的時(shí)候招拙,比如select的數(shù)據(jù)是從接口獲取并填充到組件的;又或者隱藏/顯示數(shù)組的子項(xiàng)等等措译。
基于上面的問題别凤,怎么解決呢?
json schema的定義:
{
"definitions": {
"address": {
"type": "object",
"properties": {
"street_address": {
"type": "string"
},
"city": {
"type": "string"
},
"state": {
"type": "string"
}
},
"required": [
"street_address",
"city",
"state"
]
},
"node": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"children": {
"type": "array",
"items": {
"$ref": "#/definitions/node"
}
}
}
}
},
"type": "object",
"properties": {
"billing_address": {
"title": "Billing address",
"$ref": "#/definitions/address"
},
"shipping_address": {
"title": "Shipping address",
"$ref": "#/definitions/address"
},
"tree": {
"title": "Recursive references",
"$ref": "#/definitions/node"
}
}
}
ui schema的定義
{
"ui:order": [
"shipping_address",
"billing_address",
"tree"
]
}
首先讓我們來看一看表單中的每一個(gè)項(xiàng)由什么組成领虹。
- 首先這里定義了一個(gè)fieldset规哪,顯示為Shipping address
- 其次這里的數(shù)據(jù)結(jié)構(gòu)為:Object -> [string,string,string],對(duì)應(yīng)的表單顯示為:ObjectField-> [ FieldTemplate->BaseInput, FieldTemplate->BaseInput, FieldTemplate->BaseInput ];
有沒有可能定義出ObjectField-> RowTemplate->[ ColTemplate->FormItemTemplate->BaseInput, ColTemplate->FormItemTemplate->BaseInput, ColTemplate->FormItemTemplate->BaseInput ]這樣的結(jié)構(gòu)塌衰;這里要定義多模板诉稍,只能自定義Field來滿足需求,但是模板不能夠復(fù)用最疆,很蛋疼杯巨。當(dāng)然還有很多問題需要解決,比如ColTemplate中的span努酸、pull和push如何來定義等服爷。
針對(duì)以上的問題,我們來修改一下結(jié)構(gòu)获诈。