Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

新增 useForm hook 获取 form 实例 & 支持 initialData 全局设置初始值 #1351

Merged
merged 3 commits into from
Aug 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 18 additions & 45 deletions src/form/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import classNames from 'classnames';
import useConfig from '../hooks/useConfig';
import noop from '../_util/noop';
import forwardRefWithStatics from '../_util/forwardRefWithStatics';
import type { TdFormProps, FormInstanceFunctions } from './type';
import type { TdFormProps } from './type';
import useInstance from './hooks/useInstance';
import useForm from './hooks/useForm';
import { StyledProps } from '../common';
import FormContext from './FormContext';
import FormItem from './FormItem';
Expand All @@ -15,29 +16,27 @@ export interface FormProps extends TdFormProps, StyledProps {
children?: React.ReactNode;
}

export interface FormRefInterface extends React.RefObject<unknown>, FormInstanceFunctions {
currentElement: HTMLFormElement;
}

const Form = forwardRefWithStatics(
(props: FormProps, ref) => {
const { classPrefix, form: globalFormConfig } = useConfig();

const {
style,
className,
labelWidth = '100px',
form,
labelWidth,
statusIcon,
labelAlign = 'right',
layout = 'vertical',
colon = false,
labelAlign,
layout,
colon,
initialData,
requiredMark = globalFormConfig.requiredMark,
scrollToFirstError,
showErrorMessage = true,
resetType = 'empty',
showErrorMessage,
resetType,
rules,
errorMessage = globalFormConfig.errorMessage,
preventSubmitDefault = true,
preventSubmitDefault,
disabled,
children,
onReset,
Expand All @@ -50,47 +49,20 @@ const Form = forwardRefWithStatics(

const formRef: React.RefObject<HTMLFormElement> = useRef();
const formMapRef = useRef(new Map()); // 收集所有 formItem 实例
const formInstance = useInstance(props, formRef, formMapRef);

const {
submit,
reset,
getFieldValue,
getFieldsValue,
setFieldsValue,
setFields,
validate,
validateOnly,
clearValidate,
setValidateMessage,
} = useInstance(props, formRef, formMapRef);

useImperativeHandle(ref as FormRefInterface, () => ({
currentElement: formRef.current,
submit,
reset,
getFieldValue,
getFieldsValue,
setFieldsValue,
setFields,
validate,
validateOnly,
clearValidate,
setValidateMessage,
}));
useImperativeHandle(ref, () => formInstance);
form && Object.assign(form, { ...formInstance });

function onResetHandler(e: React.FormEvent<HTMLFormElement>) {
if (preventSubmitDefault) {
e.preventDefault?.();
e.stopPropagation?.();
}
[...formMapRef.current.values()].forEach((formItemRef) => {
formItemRef?.current.resetField();
});
onReset?.({ e });
}

function onFormItemValueChange(changedValue: Record<string, unknown>) {
const allFields = getFieldsValue(true);
const allFields = formInstance.getFieldsValue(true);
onValuesChange(changedValue, allFields);
}

Expand All @@ -110,6 +82,7 @@ const Form = forwardRefWithStatics(
labelAlign,
layout,
colon,
initialData,
requiredMark,
errorMessage,
showErrorMessage,
Expand All @@ -125,7 +98,7 @@ const Form = forwardRefWithStatics(
ref={formRef}
style={style}
className={formClass}
onSubmit={submit}
onSubmit={formInstance.submit}
onReset={onResetHandler}
onKeyDown={onKeyDownHandler}
>
Expand All @@ -134,7 +107,7 @@ const Form = forwardRefWithStatics(
</FormContext.Provider>
);
},
{ FormItem, FormList },
{ useForm, FormItem, FormList },
);

Form.displayName = 'Form';
Expand Down
2 changes: 2 additions & 0 deletions src/form/FormContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const FormContext = React.createContext<{
labelAlign: TdFormProps['labelAlign'];
layout: TdFormProps['layout'];
colon: TdFormProps['colon'];
initialData: TdFormProps['initialData'];
requiredMark: TdFormProps['requiredMark'];
scrollToFirstError: TdFormProps['scrollToFirstError'];
showErrorMessage: TdFormProps['showErrorMessage'];
Expand All @@ -22,6 +23,7 @@ const FormContext = React.createContext<{
labelAlign: 'right',
layout: 'vertical',
colon: false,
initialData: {},
requiredMark: true,
scrollToFirstError: undefined,
showErrorMessage: true,
Expand Down
19 changes: 17 additions & 2 deletions src/form/FormItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ const FormItem = forwardRef<FormItemInstance, FormItemProps>((props, ref) => {
const {
colon,
layout,
initialData: initialDataFromContext,
requiredMark: requiredMarkFromContext,
labelAlign: labelAlignFromContext,
labelWidth: labelWidthFromContext,
Expand Down Expand Up @@ -85,7 +86,15 @@ const FormItem = forwardRef<FormItemInstance, FormItemProps>((props, ref) => {
const [verifyStatus, setVerifyStatus] = useState('validating');
const [resetValidating, setResetValidating] = useState(false);
const [needResetField, setNeedResetField] = useState(false);
const [formValue, setFormValue] = useState(getDefaultInitialData(children, initialData));
const [formValue, setFormValue] = useState(
getDefaultInitialData({
name,
formListName,
children,
initialData,
initialDataFromContext,
}),
);

const currentFormItemRef = useRef<FormItemInstance>(); // 当前 formItem 实例
const innerFormItemsRef = useRef([]);
Expand Down Expand Up @@ -261,7 +270,13 @@ const FormItem = forwardRef<FormItemInstance, FormItemProps>((props, ref) => {

function getResetValue(resetType: string): ValueType {
if (resetType === 'initial') {
return getDefaultInitialData(children, initialData);
return getDefaultInitialData({
name,
formListName,
children,
initialData,
initialDataFromContext,
});
}

let emptyValue: ValueType = '';
Expand Down
Loading