Antd pro-components ModalForm Instance created by `useForm` is not connect to any Form element. Forget to pass `form` prop? 解法

antd logo
Warning: Instance created by `useForm` is not connected to any Form element. Forget to pass `form` prop?

在Form元件渲染之前調用了useForm方法,會報這個錯誤,如果是在Modal中,可以給Modal加上forceRender

解法有以下幾種:

  1. modalProps.getContainer 設為 false
  2. modalProps.forceRender 設為 true
<ModalForm
  {...}
  form={form}
  width="60%"
  modalProps={{
    destroyOnClose: true,
    getContainer: false,
    forceRender: true
  }}
>
{...}
</ModalForm>

3. 使用 ref 先判斷 modal 是否已經渲染 (官方推薦解法)

import React, { useRef } from 'react'
import {
  ModalForm,
  ProForm
} from '@ant-design/pro-components'
import { Form } from 'antd'

export const ModalComponent = ({ show }) => {
  const [form] = Form.useForm<Data>()
  const preVisibleRef = useRef<boolean>()

  useEffect(() => {
    preVisibleRef.current = show

    if (!show && preVisibleRef.current) {
      form.resetFields()
    }
  }, [show])

  return (
    <ModalForm
      {...}
      form={form}
      open={show}
    >
      {...}
    </ModalForm>
  )
}

留言

目前沒有留言。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *