Skip to content

Commit

Permalink
docs(Form): How to use ref with Form HOC (#19937)
Browse files Browse the repository at this point in the history
* 为Form新增如何在函数组件中使用的例子

* 在Form FAQ中增加在函数组件中怎么正确拿到Form实例的说明

* 更新英文文档

* 按照comment修改

* 更新英文标题

* 修改英文文档FAQ的标题

* 修改英文文档里的大小写问题

* 按照豆酱的comments进行修改

* 按照comments进行修改
  • Loading branch information
chj-damon authored and zombieJ committed Nov 27, 2019
1 parent 6030431 commit 2d82b59
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
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)

0 comments on commit 2d82b59

Please sign in to comment.