与选项卡一起使用时,react-hook-form useController 出现问题

问题描述 投票:0回答:1

我已经多次尝试让这项工作成功,但不幸的是我没有运气。我正在尝试分 4 个步骤提交表单,按选项卡划分:

所以我有我的初始状态:

const initialValues = {
  step1: {
    statement: '',
    weight: '',
    statements: [],
  },
  step2: {
    statement: '',
    weight: '',
    statements: [],
  },
  step3: {
    statement: '',
    weight: '',
    statements: [],
  },
};

然后我像这样初始化表单:

const Form = () => {
  const methods = useForm({ defaultValues: initialValues });

  const onSubmit = () => {
    methods.handleSubmit((data) => console.log('data: ', data));
  };

  return (
    <form onSubmit={onSubmit}>
      <FormProvider {...methods}>
        <section>
          <TabContent
            tabsList={Object.keys(assetTypes).map((assetType) => assetType)}
            defaultTab="tab1"
          >
            {(activeTab) => {
              console.log('rendering for: ', activeTab);
              return <Feature tabName={activeTab} />;
            }}
          </TabContent>
        </section>
      </FormProvider>
    </form>
  );
};

export default Form;

然后创建 TabContents,以便我最终可以将数据写入表单状态:

import React, { memo, useEffect } from 'react';
import { useController } from 'react-hook-form';

const Feature = ({ tabName }) => {
  console.log('rendering tab', tabName); --> changes just fime
  const {
    field: { value, onChange: fieldOnChange },
  } = useController({ name: tabName });

  const onChangeStatement = (e) =>
    fieldOnChange({
      ...value,
      statement: e.target.value,
    });

  const onChangeWeight = (e) =>
    fieldOnChange({
      ...value,
      weight: e.target.value,
    });

  useEffect(() => {
    console.log('tabName: ', tabName); <--- that changes correctly
    console.log('value: ', value); <--- always points to the first state tab1
  }, [tabName, value]);

  return (
    <React.Fragment>
      <h1>{tabName}</h1>
      <input onChange={onChangeStatement} value={value.tab1?.statement} />
      <input onChange={onChangeWeight} value={value.tab2?.weight} />
    </React.Fragment>
  );
};

export default memo(Feature);

但是,每当我切换选项卡时,状态都不会指向我所在的选项卡。如果您想查看的话,这里有一个实时演示:https://stackblitz.com/edit/react-5dpii4

如果有人可以帮助我,我将非常感激

reactjs react-hooks react-hook-form
1个回答
0
投票

您需要将

tabName
属性传递给
useForm
钩子,以便它可以跟踪当前选项卡。

© www.soinside.com 2019 - 2024. All rights reserved.