import React, { Component,useCallback,useState ,useEffect} from 'react'; import { PageComponent } from "../../types/index"; import * as Tools from 'jad-tool' import { checkValidateRule,getFormData } from 'jad-tool' const createFormFieldComponent = (FormFieldContext,config) => class FormField extends React.Component< PageComponent<{ onValidateChange: (boolean)=>any }>>{ fields = {}; validate = false; name = config.name public updateFieldItem(item){ const { name = null } = item; if(!name) return this.fields[name] = item this.checkValidate() } public removeFiledItem(item){ const { name = null } = item; if(!name) return delete this.fields[name] this.checkValidate() } public checkValidate(){ const { onValidateChange } = this.props let error = false; Tools.map(this.fields,(fields)=>{ if(error) return const { rule ,value } = fields error = checkValidateRule(rule,value) }) if(this.validate !== !error && !Tools.isEmptyObject(this.fields)){ this.validate = !error onValidateChange(this.validate) } return this.validate } public getFormData(){ return getFormData(this.fields) } componentWillUnmount(){ console.log('表单组件卸载') } render(){ const { children } = this.props; return {children} } } const createFormField_middle= (FormFieldContext,config)=> ({ interrupt })=>{ class FormFieldItem extends React.Component{ removeField = null componentWillUnmount(){ console.log('表单卸载') if(Tools.isFunction(this.removeField)){ this.removeField(this.props) }else{ console.error('componentWillUnmount removeFiledItem is not function') } } render(){ const { children } = this.props; return {({updateFieldItem,removeFiledItem}) => { updateFieldItem(this.props) if(!Tools.isFunction(this.removeField)){ this.removeField = removeFiledItem } return children }} } } return(next) => (params,child) => { const render = {child} next(params,render) }} const CreateUncontrolledFormField_middle = (FormFieldContext,config)=> ({ interrupt })=>{ class FormFieldItem extends React.Component{ } return(next) => (params,child) => { next(params,child) }} export const createFormFnField = (config={}) => { config = Tools.extend({ name:`form_${Tools.getUniqueID()}`, },config) const FormFieldContext = React.createContext(null) // class const FormFieldComponent = createFormFieldComponent(FormFieldContext,config) // middle const formFieldItem_middle = createFormField_middle(FormFieldContext,config) const uncontrolledFormField_middle = CreateUncontrolledFormField_middle(FormFieldContext,config) return { FormFieldComponent, formFieldItem_middle, uncontrolledFormField_middle } }