Skip to content

Commit

Permalink
feat: formControl add valuePropName support
Browse files Browse the repository at this point in the history
  • Loading branch information
myNameIsDu committed Apr 28, 2022
1 parent 69dee5e commit 8ba9c8e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/FormControl/FormControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ export interface FormControlProps<P = any, ValueType = any>

/** Remove field value and error message when component is unmounted */
shouldResetWithUnmount?: boolean;

/** Property name of the value of the child node */
valuePropName?: string;
}

interface FormControlComponent extends React.FC<FormControlProps> {
Expand Down Expand Up @@ -95,6 +98,7 @@ const FormControl: FormControlComponent = React.forwardRef((props: FormControlPr
onBlur,
defaultValue,
shouldResetWithUnmount = false,
valuePropName = 'value',
...rest
} = props;

Expand Down Expand Up @@ -176,6 +180,10 @@ const FormControl: FormControlComponent = React.forwardRef((props: FormControlPr
const fieldHasError = Boolean(messageNode);
const ariaErrormessage = fieldHasError && controlId ? `${controlId}-error-message` : undefined;

const valueProp = {
[valuePropName]: val
};

return (
<Component className={classes} ref={ref}>
<AccepterComponent
Expand All @@ -192,7 +200,7 @@ const FormControl: FormControlComponent = React.forwardRef((props: FormControlPr
onChange={handleFieldChange}
onBlur={handleFieldBlur}
defaultValue={defaultValue ?? formDefaultValue[name]}
value={val}
{...valueProp}
/>

<FormErrorMessage
Expand Down
22 changes: 22 additions & 0 deletions src/FormControl/test/FormControlSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import Form from '../../Form';
import FormControl from '../FormControl';
import FormGroup from '../../FormGroup';
import Schema from '../../Schema';
import Input from '../../Input';

describe('FormControl', () => {
it('Should output a input', () => {
Expand Down Expand Up @@ -253,4 +254,25 @@ describe('FormControl', () => {
assert.deepEqual(refValue, { email: '' });
assert.deepEqual(refError, {});
});


it('The value should be passed using valuePropsName, when using valuePropName', () => {
let valueRef = null;
const valuePropName = 'valueName';
const WrapperInput = props => {
const { [valuePropName]: value, ...reset } = props;
valueRef = value;
return <Input value={value} {...reset} />;
};
const formVale = {
name1: '1'
};

render(
<Form formValue={formVale}>
<FormControl accepter={WrapperInput} name="name1" valuePropName={valuePropName} />
</Form>
);
expect(valueRef).to.equal(formVale.name1);
});
});

0 comments on commit 8ba9c8e

Please sign in to comment.