React-hook-form、react-tabs 和 yupResolver - TypeError: o[(intermediate value)(intermediate value)(intermediate value)] 不是函数

React-hook-form, react-tabs and yupResolver - TypeError: o[(intermediate value)(intermediate value)(intermediate value)] is not a function

提问人:Tactic Sugar 提问时间:11/16/2023 更新时间:11/16/2023 访问量:11

问:

我尝试使用react-hook-form构建一个动态表单,是的,通过这个很酷的指南:https://dev.to/franklin030601/dynamic-forms-with-react-hook-form-2ml8

我有这样的数据结构:

export const tabs: Tab[] = [
  {
    tabContent: [
      {
        label: 'Размер',
        name: 'productSize',
        placeholder: '35 px',
        sizeVariant: '15',
        type: 'text',
        validations: [
          {
            message: 'Минимум 3 символа',
            type: 'minLength',
            value: 3
          },
          {
            message: 'Обязательно к заполнению',
            type: 'required'
          }
        ],
        value: ''
      },
    ],
    tabTitle: 'Лендинг'
  },
  {
    tabContent: [
      {
        label: 'Terms and Conditions',
        name: 'terms4',
        type: 'checkbox',
        typeValue: 'boolean',
        validations: [
          {
            message: 'Accept the terms!',
            type: 'isTrue'
          }
        ],
        value: true
      },
      {
        groupTitle: 'Group 1',
        inputs: [
          {
            label: 'Terms',
            name: 'terms2',
            type: 'checkbox',
            typeValue: 'boolean',
            validations: [
              {
                message: 'Accept the terms!',
                type: 'isTrue'
              }
            ],
            value: true
          },
          {
            label: 'Checkbox 2',
            name: 'checkbox2',
            type: 'checkbox',
            typeValue: 'boolean',
            value: true
          },
          {
            label: 'Checkbox 3',
            name: 'checkbox3',
            type: 'checkbox',
            typeValue: 'boolean',
            value: false
          }
        ]
      }
    ],
    tabTitle: 'Системное'
  }
]

我在这里处理验证字段:

type YupBoolean = Yup.BooleanSchema<boolean | undefined, Yup.AnyObject, boolean | undefined>
type YupString = Yup.StringSchema<string | undefined, Yup.AnyObject, string | undefined>
type YupNumber = Yup.NumberSchema<boolean | undefined, Yup.AnyObject, number | undefined>

/** обработчик валидаций yup */
const generateValidations = (field: InputTypes) => {
  if (!field.validations) return null

  /** задает схему */
  let schema: YupBoolean | YupString = Yup[field.typeValue || 'string']()

  for (
    /** пробегается по правилам из данных validations */
    const rule of field.validations) {
    switch (rule.type) {
      case 'isTrue' : schema = (schema as YupBoolean).isTrue(rule.message); break
      case 'isEmail' : schema = (schema as YupString).email(rule.message); break
      case 'minLength': schema = (schema as YupString).min(rule?.value as number, rule.message); break
      case 'oneOf' : schema = (schema as YupString).oneOf([Yup.ref((rule as any).ref)], rule.message); break
      default : schema = schema.required(rule.message); break
    }
  }

  return schema
}

然后,我尝试使用react-tabs将表单传播到选项卡中:

/** страница тестовая */
const TestPage = () => {
  /** дата */
  const anotherForm = transformForm(tabs)

  console.log('anotherForm.validationsFields', anotherForm.validationsFields)

  /** методы из формы */
  const formMethods = useForm({
    defaultValues: { ...(anotherForm.initialValues as any) },
    mode: 'onSubmit',
    resolver: yupResolver(anotherForm.validationsFields)
  })

  /** обработчик сабмита */
  const onSubmit = (data) => {
    console.log('data', data)
  }

  return (
    <section>
      <FormProvider {...formMethods}>
        <form
          className=''
          onSubmit={formMethods.handleSubmit(onSubmit)}
        >
          <Tabs>
            <TabList>
              {anotherForm.tabs.map((tab, index) => (
                <Tab key={index}>
                  {tab.tabTitle}
                </Tab>
              ))}
            </TabList>

            {anotherForm.tabs.map((tab, index) => (
              <TabPanel key={index}>
                <>
                  <h2>
                    {tab.tabTitle}
                  </h2>
                  <Form tabContent={tab.tabContent} />
                </>
              </TabPanel>
            ))}
          </Tabs>
          <button type='submit'>
            submit
          </button>
          <TabsUnderline />
        </form>
      </FormProvider>
    </section>

验证架构如下所示: 处理后的架构

如果我不尝试将字段放在选项卡中并使用所有字段制作 1 个长页面,或者如果我关闭解析器,一切都可以正常工作。 但是如果我尝试在选项卡之间切换,我会出现错误

**TypeError: o[(intermediate value)(intermediate value)(intermediate value)] is not a function**

据我了解,这是与useForm中的上下文或模式上下文有关的东西。我无法解决它。

另一个问题:我需要通过切换选项卡在本地保存输入的数据,通过重新加载页面获取后端数据,并仅通过单击提交按钮将输入的数据发送到服务器。我不想使用任何状态管理器。我在这里以正确的方式使用react-hook-form吗?

reactjs 验证 是的 react-tabs

评论


答: 暂无答案