Ionic React在表单错误后无法选择单选按钮

huangapple go评论69阅读模式
英文:

Ionic React cannot select radio button after form error

问题

我有一个使用Ionic React和Yup进行验证动态构建的表单,这是基于来自API的信息完成的,但如果我在按下提交按钮时不选择单选按钮,单选按钮将变为不可点击,这意味着我永远无法去掉错误。

这里我创建了一个示例,其中包含一个硬编码的表单,而不是动态填充的表单,如果您在不进行任何操作的情况下点击"Save",然后您将无法选择单选按钮,但我无法确定我的问题出在哪里。

示例链接

import React, { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import {
  IonList,
  IonRadioGroup,
  IonItem,
  IonLabel,
  IonRadio,
  IonButton,
  IonContent,
  IonPage,
  setupIonicReact,
  IonInput
} from "@ionic/react";

import "@ionic/react/css/core.css";
import "@ionic/react/css/normalize.css";
import "@ionic/react/css/structure.css";
import "@ionic/react/css/typography.css";
import "@ionic/react/css/padding.css";
import "@ionic/react/css/float-elements.css";
import "@ionic/react/css/text-alignment.css";
import "@ionic/react/css/text-transformation.css";
import "@ionic/react/css/flex-utils.css";
import "@ionic/react/css/display.css";

import "./theme/variables.css";
setupIonicReact();

const validationSchema = yup.object().shape({
  q7: yup.string().required("selection is required")
});

export default function App() {
  const {
    register,
    reset,
    getValues,
    handleSubmit,
    control,
    formState: { errors }
  } = useForm({
    resolver: yupResolver(validationSchema),
    mode: "all"
  });

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <>
      <IonPage className="ion-page" id="main-content">
        <IonContent className="ion-padding">
          <div className="App">
            <form onSubmit={handleSubmit(onSubmit)}>
              <>
                values: {getValues("name")}
                <IonInput {...register("name")} />
                error: {errors["q7"]?.message}
                values: {getValues("q7")}
                <Controller
                  control={control}
                  name="q7"
                  render={({ field: { onChange, value, ref } }) => (
                    <>
                      {console.log(value)}
                      <IonList>
                        <IonRadioGroup
                          ref={ref}
                          defaultValue=""
                          value={value ?? ""}
                          onIonChange={({ detail: { value } }) =>
                            onChange(value ?? "")
                          }
                        >
                          <IonItem>
                            <IonLabel>Type 2</IonLabel>
                            <IonRadio value="2" slot="start" />
                          </IonItem>

                          <IonItem>
                            <IonLabel>Type 4</IonLabel>
                            <IonRadio slot="start" value="4" />
                          </IonItem>

                          <IonItem>
                            <IonLabel>Type 6</IonLabel>
                            <IonRadio slot="start" value="6" />
                          </IonItem>
                        </IonRadioGroup>
                      </IonList>
                    </>
                  )}
                />
                <br />
                <IonButton type="submit">Save</IonButton>
              </>
            </form>
          </div>
        </IonContent>
      </IonPage>
    </>
  );
}

这是您提供的代码的翻译部分。如果需要进一步的帮助,请随时提出。
<details>
<summary>英文:</summary>
I have a form which is dynamically built using Ionic React and Yup for validation, this is done based on information coming from an API but I have an issue if I do not select a radio button when I press submit the radio buttons become unclickable which means I can never get the error away.
I have created an example here with a hardcoded form rather than it being populated dynamically and if you click Save without doing anything you will then not be able to select the radio buttons but I can&#39;t workout where my issue is coming from.
[Link to example of my issue][1]
[1]: https://codesandbox.io/s/jolly-khayyam-9qbvuu?file=/src/App.tsx
Edit:
Here is the main section of code not working:
import React, { useEffect } from &quot;react&quot;;
import { Controller, useForm } from &quot;react-hook-form&quot;;
import * as yup from &quot;yup&quot;;
import { yupResolver } from &quot;@hookform/resolvers/yup&quot;;
import {
IonList,
IonRadioGroup,
IonItem,
IonLabel,
IonRadio,
IonButton,
IonContent,
IonPage,
setupIonicReact,
IonInput
} from &quot;@ionic/react&quot;;
/* Core CSS required for Ionic components to work properly */
import &quot;@ionic/react/css/core.css&quot;;
/* Basic CSS for apps built with Ionic */
import &quot;@ionic/react/css/normalize.css&quot;;
import &quot;@ionic/react/css/structure.css&quot;;
import &quot;@ionic/react/css/typography.css&quot;;
/* Optional CSS utils that can be commented out */
import &quot;@ionic/react/css/padding.css&quot;;
import &quot;@ionic/react/css/float-elements.css&quot;;
import &quot;@ionic/react/css/text-alignment.css&quot;;
import &quot;@ionic/react/css/text-transformation.css&quot;;
import &quot;@ionic/react/css/flex-utils.css&quot;;
import &quot;@ionic/react/css/display.css&quot;;
/* Theme variables */
import &quot;./theme/variables.css&quot;;
setupIonicReact();
const validationSchema = yup.object().shape({
q7: yup.string().required(&quot;selection is required&quot;)
});
export default function App() {
const {
register,
reset,
getValues,
handleSubmit,
control,
formState: { errors }
} = useForm({
resolver: yupResolver(validationSchema),
mode: &quot;all&quot;
});
const onSubmit = (data: any) =&gt; {
console.log(data);
};
// useEffect(() =&gt; {
//   reset({
//     // q7: &quot;6&quot;
//   });
// }, [reset]);
return (
&lt;React.Fragment&gt;
&lt;IonPage className=&quot;xion-page&quot; id=&quot;main-cntent&quot;&gt;
&lt;IonContent className=&quot;ion-padding&quot;&gt;
&lt;div className=&quot;App&quot;&gt;
&lt;form onSubmit={handleSubmit(onSubmit)}&gt;
&lt;&gt;
values:{getValues(&quot;name&quot;)}
&lt;IonInput {...register(&quot;name&quot;)}&gt;&lt;/IonInput&gt;
error:{errors[&quot;q7&quot;]?.message}
values:{getValues(&quot;q7&quot;)}
&lt;Controller
control={control}
name=&quot;q7&quot;
render={({ field: { onChange, value, ref } }) =&gt; (
&lt;&gt;
{console.log(value)}
&lt;IonList&gt;
&lt;IonRadioGroup
ref={ref}
defaultValue=&quot;&quot;
// allowEmptySelection={true}
value={value ?? &quot;&quot;}
onIonChange={({ detail: { value } }) =&gt;
onChange(value ?? &quot;&quot;)
}
&gt;
&lt;IonItem&gt;
&lt;IonLabel&gt;Type 2&lt;/IonLabel&gt;
&lt;IonRadio value=&quot;2&quot; slot=&quot;start&quot; /&gt;
&lt;/IonItem&gt;
&lt;IonItem&gt;
&lt;IonLabel&gt;Type 4&lt;/IonLabel&gt;
&lt;IonRadio slot=&quot;start&quot; value=&quot;4&quot; /&gt;
&lt;/IonItem&gt;
&lt;IonItem&gt;
&lt;IonLabel&gt;Type 6&lt;/IonLabel&gt;
&lt;IonRadio slot=&quot;start&quot; value=&quot;6&quot; /&gt;
&lt;/IonItem&gt;
&lt;/IonRadioGroup&gt;
&lt;/IonList&gt;
&lt;/&gt;
)}
/&gt;
&lt;br /&gt;
&lt;IonButton type=&quot;submit&quot;&gt;Save&lt;/IonButton&gt;
&lt;/&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/IonContent&gt;
&lt;/IonPage&gt;
&lt;/React.Fragment&gt;
);
}
</details>
# 答案1
**得分**: 0
你的问题是应该传递一个 onChange 函数的 JavaScript 事件。在 onIonChange 中修改事件并添加自定义属性。但实际上,你传递给函数的是一个值,而不是一个事件。
你可以在文档中找到标准的 JavaScript 事件在 onIonChange 中的位置,或者只需使用 setValue。
```jsx
<IonRadioGroup
{...field}
onIonChange={
(event) => {
setValue('q7', event.detail.value)
}
}
>

查看示例

英文:

Your problem is that you should pass in onChange function js event.
In onIonChange modified event with custom properties.
But you actually passed a value to the function, not an event.

You can find in docks where is standard js event in onIonChange or just setValue

 &lt;IonRadioGroup
{...field}
onIonChange={
(event) =&gt; {
setValue(&#39;q7&#39;, event.detail.value)
}
}
&gt;

https://codesandbox.io/s/crimson-breeze-d9fptl?file=/src/App.tsx:2253-2591

huangapple
  • 本文由 发表于 2023年2月19日 07:55:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497154.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定