UNPKG

2.66 kBTypeScriptView Raw
1import React, { Component } from 'react'
2import { View, StyleSheet, DeviceEventEmitter } from 'react-native'
3import { List } from '@sishuguojixuefu/antd-mobile-rn'
4import { createForm } from 'rc-form'
5import FormItem from './components'
6import FormPropsType from './utils/FormPropsType'
7import getFieldDecorator from './utils/getFieldDecorator'
8
9class Form extends Component<FormPropsType, any> {
10 static defaultProps = {
11 noBorder: true,
12 }
13
14 constructor(props: FormPropsType) {
15 super(props)
16 // 业务驱动
17 const childs = this._getChilds()
18 if (childs && childs.length) {
19 childs.forEach((item: any) => {
20 if (item.props.custom) {
21 const { id, initialValue, rules } = item.props
22 this[id] = getFieldDecorator(props.form, id, initialValue, rules, props.options)
23 }
24 })
25 }
26 }
27
28 // 兼容单个child
29 private _getChilds = () => {
30 const { children } = this.props
31 let childs: any = children
32 if (children && !children.length) {
33 childs = [children]
34 }
35 return childs
36 }
37
38 private _onChange = () => {
39 DeviceEventEmitter.emit('SsDynamicFormValueChanged', {
40 values: this.props.form.getFieldsValue(),
41 })
42 }
43
44 render() {
45 const { items, renderHeader, renderFooter, form, noBorder, style } = this.props
46 const childs = this._getChilds()
47 return (
48 <List
49 renderHeader={renderHeader}
50 renderFooter={renderFooter}
51 style={[styles.container, style]}
52 noBorder={noBorder}
53 >
54 {items && items.length
55 ? items.map(item => {
56 if (Object.keys(FormItem).indexOf(item.componentName) >= 0) {
57 return React.createElement(FormItem[item.componentName], {
58 key: item.props.id,
59 form,
60 onChange: () => this._onChange(),
61 ...item.props,
62 })
63 }
64 return null
65 })
66 : null}
67 {childs && childs.length
68 ? childs.map((item: any, index: number) => {
69 const child = React.cloneElement(item, {
70 key: item.props.id || index.toString(),
71 form,
72 id: item.props.id,
73 onChange: () => this._onChange(),
74 ...item.props,
75 })
76 return item.props.custom ? this[item.props.id](child) : child
77 })
78 : null}
79 <View style={{ height: noBorder ? 1 : 0 }} />
80 </List>
81 )
82 }
83}
84
85const styles = StyleSheet.create({
86 container: {
87 backgroundColor: '#ffffff',
88 flex: 1,
89 },
90})
91
92export default createForm({})(Form)