如何在 Ionic Modal 中使用 react-hook-form?

How to use react-hook-form inside Ionic Modal?

我正在尝试将 react-hook-form 与我的 Ionic React 应用程序一起使用。我正在使用这个简单的表格:

const Form: React.FC<{ color: string }> = ({ color }) => {
  const { handleSubmit, register } = useForm();

  const onSubmit = (data: any) => {
    console.log(`%c${JSON.stringify(data)}`, `color: ${color}`);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input ref={register} name="name" type="text" />
      <input ref={register} name="surname" type="text" />
      <input type="submit" />
    </form>
  );
};

该组件运行良好,但是当我尝试在 IonModal 组件中使用它时,onSubmit 处理程序没有显示任何内容。

const App: React.FC = () => {
  const [showModal, setShowModal] = React.useState(false);

  return (
    <IonApp>
      <Form color="green" />
      <IonModal
        isOpen={showModal}
        onDidDismiss={() => setShowModal(false)}
        children={<Form color="red" />}
      />
      <IonButton onClick={() => setShowModal(true)}>Open Modal</IonButton>
    </IonApp>
  );
};

如果我提交第一个 Form,数据会在控制台中正确打印,但如果我在 IonModal 组件中提交第二个则不会。 Here's 显示此行为的示例。

在此处查看工作示例...

https://codesandbox.io/s/ionic-modal-form-bug-48weq

我能够使用来自 react-hook-form

Controller
        <IonItem>
          <Controller
            as={<IonInput />}
            name="name"
            control={control}
            rules={{ required: true }}
            onChangeName="onIonChange"
            onChange={([selected]: any) => {
              return selected.detail.value;
            }}
          />
        </IonItem>

完整博客 post 此处 Using React Hook Form with Ionic React Components

我在这里遇到了一些类似的情况,我通过渲染 IonInputonIonChange 调用 onChange 我们需要的值解决了这个问题:

<Controller
                    render={({ onChange, value }) => (
                      <IonInput
                        value={value}
                        type="tel"
                        placeholder="AA"
                        onIonChange={(e: CustomEvent<InputChangeEventDetail>) =>
                          onChange(
                            String(e.detail.value!).length < 2
                              ? `0${e.detail.value!}`
                              : e.detail.value!
                          )
                        }
                      />
                    )}
                    rules={{
                      required: true,
                    }}
                    name="expiryMonth"
                    control={control}
                  />

我们不是在 Controller 组件中更改值,而是获取更改值并在 onIonChange 函数内部处理它,并将结果值传递给 Controller组件的改变方法。