阅读 197

antd使用技巧

Form数据的收集和初始化

@Form.create({
    mapPropsToFields: (props) => {
        const { formData } = props;
        const keys = Object.keys(formData);
        const newFormData = {};
        for (let i = 0; i < keys.length; i++) {
            newFormData[keys[i]] = Form.createFormField({
                ...formData[keys[i]],
                value: formData[keys[i]] && formData[keys[i]].value,
            });
        }
        return newFormData;
    },
    onFieldsChange(props, fields) {
        let baseKey = ['deptcode', 'reportYear', 'reportMonth', 'deptname', 'deptPeopleNow', 'deptPeoplePre', 'certificatePeopleNow', 'certificatePeoplePre', 'premiumTotal', 'premiumPre', 'turnoverTotal', 'turnoverPre', 'profitNow', 'profitPre'];
        const keys = Object.keys(fields);
        let key = keys[0]; // 基本信息中的key / property / life
        let newFields = {};
        if (baseKey.includes(key)) { // 对于普通的formItem
            props.onFormChange(fields);
        } else { // 成组增加的formItem
            let subFields = fields[key] || {};
            let subFieldsKey = Object.keys(subFields)[0];
            if (subFieldsKey) {
                let arr = subFields[subFieldsKey] || [];
                let realyFieldsKey = Object.keys(arr)[0];
                if (!realyFieldsKey) return;
                let value = arr[realyFieldsKey];
                newFields = {
                    [value.name]: value,
                };
                props.onFormChange(newFields);
            }

        }
    },
})
// 改变表单数据时触发 onFormChange
onFormChange = (changedFields) => {
    this.setState(({ formData }) => ({
        formData: { ...formData, ...changedFields },
    }));
}
// 通过mapPropsToFields将数据显示在页面上 接个返回的表单数据需要进行格式化
export function getFormatFormData(obj, options) {
    const { dateFields, arrayFormItemFields, selectFields, objectFields, imgFields } = options;
    if (!obj) {
        return {};
    }
    let result = {};
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            if (dateFields && dateFields.length > 0 && inArray(key, dateFields) !== -1) {
                if (isArray(obj[key])) {
                    result[key] = {
                        value: obj[key].map(item => item && moment(item)),
                    };
                } else {
                    result[key] = {
                        value: obj[key] && moment(obj[key]),
                    };
                }

            } else if (arrayFormItemFields && arrayFormItemFields.length > 0 && inArray(key, arrayFormItemFields) !== -1) {
                (obj[key] || []).forEach((item, index) => {
                    for (let curKey in item) {
                        if (item.hasOwnProperty(curKey)) {
                            let newKey = key + curKey.substring(0, 1).toUpperCase() + curKey.substring(1, curKey.length) + 's[' + index + ']';
                            result[newKey] = {
                                value: item[curKey],
                            };
                        }
                    }
                });
            } else if (selectFields && selectFields.length > 0 && inArray(key, selectFields) !== -1) {
                result[key] = {
                    value: (obj[key] !== null && obj[key] !== undefined && obj[key].toString()) || undefined,
                };
            } else if (objectFields && objectFields.length > 0 && inArray(key, objectFields) !== -1) {
                for (let objKey in obj[key]) {
                    if (obj[key].hasOwnProperty(objKey)) {
                        result[objKey] = {
                            value: obj[key][objKey],
                        };
                    }
                }
            } else if (imgFields && imgFields.length > 0 && inArray(key, imgFields) !== -1) {
                let fieldList = [];
                (obj[key] || []).forEach((item, index) => {
                    if (item) {
                        let current = item.split('/');
                        let name = current[current.length - 1];
                        fieldList.push({
                            key: -1 - index,
                            uid: -1 - index,
                            name: name,
                            status: 'done',
                            url: item,
                        });
                    }
                });
                result[key] = { value: fieldList };
            } else {
                result[key] = { value: obj[key] };
            }
        }
    }
    return result;
}
复制代码

对于modal中的表单

通过modalVisible控制modal是否可见,以及modal的加载和销毁.对于modal中的数据,可以通过initialValue进行初始化

{modalVisible ? (<EditModal
    formData={formData}
    closeModal={this.closeModal}
    modalType={modalType}
    modalVisible={modalVisible}
    handlePageSearch={this.handlePageSearch}
    insuranceCityData={insuredCityList}
    issuingTypeList={issuingTypeList}
    licensedCityData={cities}
/>) : null}

<FormItem {...modalFormItemLayout} label="城市">
    {
        getFieldDecorator('cityId', {
            initialValue: cityId && cityId + '',
            rules: [{ required: true, message: '请选择城市' }],
            onChange: (value, options) => {
                setFieldsValue({
                    'cityName': options.props.children,
                });
            },
        })(<Select
            allowClear
            showSearch
            placeholder="请选择"
            onChange={this.handleCityChange}
            defaultActiveFirstOption={false}
            optionFilterProp="children"
            >
            {
                getSelectOptions([{ cityId: -1 , cityName: '全部' }], cityData, ['cityId', 'cityName'])
            }
        </Select>)
    }
</FormItem>
复制代码
/**
 * 获取Select中选择项
 * @param defOption
 * @param otherOptions
 * @param attributesRules
 * @returns {Array|*|{inline, annotation}}
 */
function getSelectOptions(defOption = [], otherOptions = [], fields = ['id', 'name'], attributesRules = []) {
    const options = defOption.concat(otherOptions);
    return options.map((option) => {
        const attributes = {};
        if (attributesRules && attributesRules.length > 0) {
            attributesRules.forEach((attribute) => {
                const result = attribute.split('|');
                if (result.length > 1) {
                    const valueFields = result[1].split('&');
                    attributes[result[0]] = valueFields.map(valueField => option[valueField]).join('');
                }
            });
        }
        return (
            <Option key={option[fields[0]].toString()} {...attributes}>
                {option[fields[1]]}
            </Option>
        );
    });
}
复制代码

Form-批量增加一组表单

通过getFieldDecorator进行装饰时, 赋值为number[${k}]number{k},他们对应的值分别为number[k]和fields[number{k}];

<FormItem>
    {
        getFieldDecorator(`number[${k}]`)(<Select
            placeholder="请选择"
            defaultActiveFirstOption={false}
            style={config.selectStyle}
            disabled={!canEdit}
        >
            <Option value='0'>0-0</Option>
            <Option value='1'>0-1</Option>
        </Select>)
    }
</FormItem>

复制代码