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

feat: support multiple name #663

Closed
Closed
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
3 changes: 3 additions & 0 deletions docs/demo/multiple.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## useWatch

<code src="../examples/multiple.tsx"></code>
10 changes: 7 additions & 3 deletions docs/examples/components/Input.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import React from 'react';
import React, { InputHTMLAttributes } from 'react';

const Input = (props: any) => {
return <input {...props} />;
};

const CustomizeInput = ({ value = '', ...props }: any) => (
<div style={{ padding: 10 }}>
const CustomizeInput = ({
value = '',
style,
...props
}: { value?: string } & InputHTMLAttributes<HTMLInputElement>) => (
<div style={{ padding: 10, ...style }}>
<Input style={{ outline: 'none' }} value={value} {...props} />
</div>
);
Expand Down
64 changes: 64 additions & 0 deletions docs/examples/multiple.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import React from 'react';
import Form, { Field } from 'rc-field-form';
import Input from './components/Input';

const RangeInput = ({
value = [],
onChange,
}: {
value?: string[];
onChange?: (value: string[]) => void;
}) => {
const [one, two] = value;

return (
<div style={{ display: 'flex' }}>
<Input style={{ padding: 0 }} value={one} onChange={e => onChange([e.target.value, two])} />
<Input style={{ padding: 0 }} value={two} onChange={e => onChange([one, e.target.value])} />
</div>
);
};
type FieldType = { one?: string; two?: string };

export default () => {
const [form] = Form.useForm();
return (
<>
<Form
form={form}
initialValues={{ one: '11', two: '22' }}
onFinish={v => console.log('submit values', v)}
>
<Field<FieldType> names={['one', 'two']}>
<RangeInput />
</Field>
{/* <Field<FieldType> name="two">
<Input />
</Field> */}
<button type="submit">submit</button>
</Form>
<button
onClick={() => {
console.log('values', form.getFieldsValue());
console.log('values all', form.getFieldsValue(true));
}}
>
getFieldsValue
</button>
<button
onClick={() => {
form.setFields([
{ name: 'name', value: 'name' },
{ name: 'age', value: 'age' },
]);
}}
>
setFields
</button>
<button onClick={() => form.resetFields()}>resetFields</button>
<button onClick={() => form.setFieldsValue({ name: `${form.getFieldValue('name') || ''}1` })}>
setFieldsValue
</button>
</>
);
};
65 changes: 45 additions & 20 deletions src/Field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export interface InternalFieldProps<Values = any> {
dependencies?: NamePath[];
getValueFromEvent?: (...args: EventArgs) => StoreValue;
name?: InternalNamePath;
names?: InternalNamePath[];
normalize?: (value: StoreValue, prevValue: StoreValue, allValues: Store) => StoreValue;
rules?: Rule[];
shouldUpdate?: ShouldUpdate<Values>;
Expand Down Expand Up @@ -99,8 +100,9 @@ export interface InternalFieldProps<Values = any> {
}

export interface FieldProps<Values = any>
extends Omit<InternalFieldProps<Values>, 'name' | 'fieldContext'> {
extends Omit<InternalFieldProps<Values>, 'name' | 'names' | 'fieldContext'> {
name?: NamePath<Values>;
names?: NamePath<Values>[];
}

export interface FieldState {
Expand Down Expand Up @@ -194,11 +196,24 @@ class Field extends React.Component<InternalFieldProps, FieldState> implements F
};

// ================================== Utils ==================================
public getNamePath = (): InternalNamePath => {
const { name, fieldContext } = this.props;
public getNamePath = (name?: InternalNamePath): InternalNamePath => {
const { name: propsName, fieldContext } = this.props;
const _name = name ?? propsName;

const { prefixName = [] }: InternalFormInstance = fieldContext;

return _name !== undefined ? [...prefixName, ..._name] : [];
};

public getNamesPath = (): InternalNamePath | InternalNamePath[] => {
const { name, names, fieldContext } = this.props;

const { prefixName = [] }: InternalFormInstance = fieldContext;
if (name) {
return name !== undefined ? [...prefixName, ...name] : [];
}

return name !== undefined ? [...prefixName, ...name] : [];
return names !== undefined ? names.map(name => [...prefixName, ...name]) : [];
};

public getRules = (): RuleObject[] => {
Expand Down Expand Up @@ -554,9 +569,15 @@ class Field extends React.Component<InternalFieldProps, FieldState> implements F

// ============================== Field Control ==============================
public getValue = (store?: Store) => {
const { names } = this.props;
const { getFieldsValue }: FormInstance = this.props.fieldContext;
const namePath = this.getNamePath();
return getValue(store || getFieldsValue(true), namePath);
if (names) {
const namesValue = names.map(name => {
return getValue(store || getFieldsValue(true), this.getNamePath(name));
});
return namesValue;
}
return getValue(store || getFieldsValue(true), this.getNamePath());
};

public getControlled = (childProps: ChildProps = {}) => {
Expand All @@ -573,7 +594,7 @@ class Field extends React.Component<InternalFieldProps, FieldState> implements F
const mergedValidateTrigger =
validateTrigger !== undefined ? validateTrigger : fieldContext.validateTrigger;

const namePath = this.getNamePath();
const namesPath = this.getNamesPath();
const { getInternalHooks, getFieldsValue }: InternalFormInstance = fieldContext;
const { dispatch } = getInternalHooks(HOOK_MARK);
const value = this.getValue();
Expand All @@ -593,7 +614,6 @@ class Field extends React.Component<InternalFieldProps, FieldState> implements F
);
});
}

const control = {
...childProps,
...valueProps,
Expand All @@ -617,11 +637,12 @@ class Field extends React.Component<InternalFieldProps, FieldState> implements F
if (normalize) {
newValue = normalize(newValue, value, getFieldsValue(true));
}

dispatch({
type: 'updateValue',
namePath,
value: newValue,
namesPath.forEach((name, index) => {
dispatch({
type: 'updateValue',
namePath: this.getNamePath(name),
value: newValue[index],
});
});

if (originTriggerFunc) {
Expand All @@ -645,10 +666,12 @@ class Field extends React.Component<InternalFieldProps, FieldState> implements F
if (rules && rules.length) {
// We dispatch validate to root,
// since it will update related data with other field with same name
dispatch({
type: 'validateField',
namePath,
triggerName,
namesPath.forEach(name => {
dispatch({
type: 'validateField',
namePath: this.getNamePath(name),
triggerName,
});
});
}
};
Expand Down Expand Up @@ -681,14 +704,15 @@ class Field extends React.Component<InternalFieldProps, FieldState> implements F
}
}

function WrapperField<Values = any>({ name, ...restProps }: FieldProps<Values>) {
function WrapperField<Values = any>({ name, names, ...restProps }: FieldProps<Values>) {
const fieldContext = React.useContext(FieldContext);
const listContext = React.useContext(ListContext);
const namePath = name !== undefined ? getNamePath(name) : undefined;
const namesPath = names !== undefined ? names.map(name => getNamePath(name)) : undefined;

let key: string = 'keep';
if (!restProps.isListField) {
key = `_${(namePath || []).join('_')}`;
key = `_${(namePath || namesPath || []).join('_')}`;
}

// Warning if it's a directly list field.
Expand All @@ -697,7 +721,7 @@ function WrapperField<Values = any>({ name, ...restProps }: FieldProps<Values>)
process.env.NODE_ENV !== 'production' &&
restProps.preserve === false &&
restProps.isListField &&
namePath.length <= 1
(namePath.length <= 1 || namesPath.length <= 1)
) {
warning(false, '`preserve` should not apply on Form.List fields.');
}
Expand All @@ -706,6 +730,7 @@ function WrapperField<Values = any>({ name, ...restProps }: FieldProps<Values>)
<Field
key={key}
name={namePath}
names={namesPath}
isListField={!!listContext}
{...restProps}
fieldContext={fieldContext}
Expand Down
7 changes: 4 additions & 3 deletions src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ export interface FieldEntity {
isPreserve: () => boolean;
validateRules: (options?: InternalValidateOptions) => Promise<RuleError[]>;
getMeta: () => Meta;
getNamePath: () => InternalNamePath;
getNamePath: (name?: InternalNamePath) => InternalNamePath;
getNamesPath: () => InternalNamePath | InternalNamePath[];
getErrors: () => string[];
getWarnings: () => string[];
props: {
Expand Down Expand Up @@ -240,8 +241,8 @@ type RecursivePartial<T> = NonNullable<T> extends object
[P in keyof T]?: NonNullable<T[P]> extends (infer U)[]
? RecursivePartial<U>[]
: NonNullable<T[P]> extends object
? RecursivePartial<T[P]>
: T[P];
? RecursivePartial<T[P]>
: T[P];
}
: T;

Expand Down
Loading