Skip to content

Commit 66da1e4

Browse files
committed
feat: added possibility to form added field name as default
1 parent 7d04995 commit 66da1e4

File tree

3 files changed

+24
-3
lines changed

3 files changed

+24
-3
lines changed

src/Field.tsx

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
defaultGetValueFromEvent,
2626
getNamePath,
2727
getValue,
28+
mountNameByPath,
2829
} from './utils/valueUtil';
2930

3031
const EMPTY_ERRORS: any[] = [];
@@ -490,9 +491,16 @@ class Field extends React.Component<InternalFieldProps, FieldState> implements F
490491
// Support render props
491492
if (typeof children === 'function') {
492493
const meta = this.getMeta();
493-
494494
return {
495-
...this.getOnlyChild(children(this.getControlled(), meta, this.props.fieldContext)),
495+
...this.getOnlyChild(
496+
children(
497+
this.getControlled({
498+
name: mountNameByPath(this.getNamePath()),
499+
}),
500+
meta,
501+
this.props.fieldContext,
502+
),
503+
),
496504
isFunction: true,
497505
};
498506
}
@@ -610,9 +618,13 @@ class Field extends React.Component<InternalFieldProps, FieldState> implements F
610618
if (isFunction) {
611619
returnChildNode = child;
612620
} else if (React.isValidElement(child)) {
621+
const theProps = (child as React.ReactElement).props;
613622
returnChildNode = React.cloneElement(
614623
child as React.ReactElement,
615-
this.getControlled((child as React.ReactElement).props),
624+
this.getControlled({
625+
...theProps,
626+
name: theProps?.name ?? mountNameByPath(this.getNamePath()),
627+
}),
616628
);
617629
} else {
618630
warning(!child, '`children` of Field is not validate ReactElement.');

src/Form.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@ const Form: React.ForwardRefRenderFunction<FormInstance, FormProps> = (
157157
return (
158158
<Component
159159
{...restProps}
160+
name={name}
160161
onSubmit={(event: React.FormEvent<HTMLFormElement>) => {
161162
event.preventDefault();
162163
event.stopPropagation();

src/utils/valueUtil.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,14 @@ export function getNamePath(path: NamePath | null): InternalNamePath {
1717
return toArray(path);
1818
}
1919

20+
export function mountNameByPath(path: NamePath | null): string {
21+
if (Array.isArray(path)) {
22+
return path.join('.');
23+
}
24+
25+
return `${path || ''}`;
26+
}
27+
2028
export function cloneByNamePathList(store: Store, namePathList: InternalNamePath[]): Store {
2129
let newStore = {};
2230
namePathList.forEach(namePath => {

0 commit comments

Comments
 (0)