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

docs(Form): 如何在函数组件中拿到 form 实例 #19937

Merged
merged 9 commits into from
Nov 27, 2019
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
35 changes: 35 additions & 0 deletions components/form/index.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,3 +275,38 @@ validator(rule, value, callback) => {
}
}
```

### Get form instance from function component

You can combine `forwardRef` with `useImperativeHandle` to get form instance:

```tsx
import React, { forwardRef, useImperativeHandle } from 'react';
import Form, { FormComponentProps } from 'antd/lib/form/Form';

const FCForm = forwardRef<FormComponentProps, FCFormProps>(({ form, onSubmit }, ref) => {
useImperativeHandle(ref, () => ({
form,
}));
`...the rest of your form`;
});
const EnhancedFCForm = Form.create<FCFormProps>()(FCForm);
```

You can use your form component like this:

```tsx
const TestForm = () => {
const formRef = createRef<Ref>();
return (
<EnhancedFCForm
onSubmit={() => console.log(formRef.current!.form.getFieldValue('name'))}
wrappedComponentRef={formRef}
/>
);
};
```

Online demo:

[![Edit wrappedComponentRef-in-function-component](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/wrappedcomponentref-in-function-component-fj43c?fontsize=14&hidenavigation=1&theme=dark)
35 changes: 35 additions & 0 deletions components/form/index.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,3 +277,38 @@ validator(rule, value, callback) => {
}
}
```

### 如何在函数组件中拿到 form 实例?

你需要通过 `forwardRef` 和 `useImperativeHandle` 的组合使用来实现在函数组件中正确拿到 form 实例:

```tsx
import React, { forwardRef, useImperativeHandle } from 'react';
import Form, { FormComponentProps } from 'antd/lib/form/Form';

const FCForm = forwardRef<FormComponentProps, FCFormProps>(({ form, onSubmit }, ref) => {
useImperativeHandle(ref, () => ({
form,
}));
`...the rest of your form`;
});
const EnhancedFCForm = Form.create<FCFormProps>()(FCForm);
```

使用表单组件可以写成这样:

```tsx
const TestForm = () => {
const formRef = createRef<Ref>();
return (
<EnhancedFCForm
onSubmit={() => console.log(formRef.current!.form.getFieldValue('name'))}
wrappedComponentRef={formRef}
/>
);
};
```

在线示例:

[![Edit wrappedComponentRef-in-function-component](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/wrappedcomponentref-in-function-component-fj43c?fontsize=14&hidenavigation=1&theme=dark)