4

我有一个反应最终形式的表格。该组件公开了 values 字段。此字段包含表单内更改的所有字段。问题是,我想从外部访问这些值。

     <Form onSubmit={onSubmit} render={({handleSubmit,values}) => 
       ...
       {JSON.stringify(values)} <- this works
     </Form>
<div>
{JSON.stringify(values)} <- this is outside, it doesn't work
</div>

我想避免为了能够访问这些值而将所有内容都塞进表单中。有什么方法可以在外部访问它,或者以某种方式至少从外部传递一个值/setValues 以使这些值在表单之外可见?

4

1 回答 1

3

The simplest way I found to get the form state outside the form is to use a MutableRefObject to get a reference to the form instance that is available inside the form.

Steps to achieve this:

  1. Create a MutableRefObject (it is basically just a ref object whose current value can be changed)
const formRef: React.MutableRefObject<FormApi> = useRef(null);

If you have interfaces for the form, you can add the form interface like this to get typings for the properties we can access through this reference:

const formRef: React.MutableRefObject<FormApi<IForm, Partial<IForm>>> = useRef(null);
  1. Inside the <Form>, attach the form instance to the MutableRefObject we just created:
<Form onSubmit={onSubmitHandler}>
    {({ handleSubmit, submitting, form, dirty }) => {
        // form reference to access for outside
        formRef.current = form;
  1. Now you can use formRef to access all properties described here in Final Form Docs - 'FormAPi' like this:
formRef.current.getFieldState();
formRef.current.change('fieldName',"value");

Explanation:

This method essentially creates a ref object and attaches the form instance to the object, and since it is a MutableRefObject, it can be changed without causing a re-render. Now, the entire form state as well as modifications to the form can be accessed and controlled from anywhere.

于 2021-08-16T14:28:33.767 回答