1

我正在尝试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组件内提交第二个,则不会。 这是一个显示此行为的示例。

4

2 回答 2

3

请参阅此处的工作示例...

https://codesandbox.io/s/ionic-modal-form-b​​ug-48weq

我能够让它与来自 react-hook-form的控制器一起工作

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

完整的博客文章使用 React Hook Form 和 Ionic React 组件

于 2020-03-15T21:06:17.400 回答
0

我在这里遇到了一些类似的情况,我通过 使用我们需要的值渲染IonInputwithonIonChange调用来解决它: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组件的更改方法。

于 2020-12-16T10:17:23.620 回答