【发布时间】:2022-01-21 19:56:19
【问题描述】:
我是 Ionic 的新手。我创建了一个简单的表单,其中包含 react-hook-form Controller 的 Title 和 Message 字段。以至于“as”出现了错误
import * as React from "react";
import { IonCard, IonCardContent, IonCardHeader, IonContent, IonHeader, IonTextarea, IonInput, IonLabel, IonPage, IonItem, IonTitle, IonToolbar, IonButton } from '@ionic/react';
import ExploreContainer from '../components/ExploreContainer';
import './Home.css';
import { Controller, useForm } from "react-hook-form";
const Home: React.FC = () => {
const initialValues = {
title: "",
body: ""
}
const { control, reset, handleSubmit, formState} = useForm({
defaultValues: initialValues
});
const onSubmit = (data: any) => {
alert(JSON.stringify(data, null, 2));
}
const resetForm = () => {
reset(initialValues);
}
// const renderErrorMessage = (_key : string ) => {
// let theErrors = (errors as any)[_key];
// return <span>theErrors.message || "This Is A Required Field"</span>
// }
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle size="large">Form Test - React Hook Form</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent fullscreen>
<IonCard>
<IonCardHeader>Test Input Form</IonCardHeader>
</IonCard>
<IonCardContent>
<form onSubmit={handleSubmit(onSubmit)}>
<IonItem>
<IonLabel>Title</IonLabel>
<Controller
as = {IonInput}
control={control}
onChangeName="onIonChange"
onChange={(selected:any) => {
return selected.detail.value;
}}
name="title"
rules={{
required: true,
minLength: { value: 4, message: "Must be 4 chars long" }
}}
/>
</IonItem>
{/* {errors.title ? renderErrorMessage("title") : null} */}
<IonItem>
<IonLabel>Body</IonLabel>
<Controller
as = {<IonTextarea rows={5}></IonTextarea>}
control={control}
onChangeName="onIonChange"
onChange={(selected:any) => {
return selected.detail.value;
}}
name="body"
rules={{
required: true,
minLength: { value: 10, message: "Must be 10 chars long" }
}}
/>
</IonItem>
{/* {errors.body ? renderErrorMessage("body") : null} */}
<IonButton type="submit">SAVE</IonButton>
<IonButton onClick={() => resetForm()}>Reset Form</IonButton>
</form>
</IonCardContent>
</IonContent>
</IonPage>
);
};
export default Home;
Visual Studio Code 在定义输入字段时在控制器标签中的 as 关键字下方显示错误行。我已经安装了 react-hook-form 库
离子:
离子 CLI:6.18.1 离子框架:@ionic/react 6.0.1
电容器:
电容器 CLI:3.3.3 @capacitor/android:未安装 @电容器/核心:3.3.3 @capacitor/ios : 未安装
实用程序:
cordova-res : 未全局安装 本机运行:1.5.0
系统:
NodeJS : v16.13.1 (C:\Program Files\nodejs\node.exe) npm:8.1.2 操作系统:Windows 10
【问题讨论】:
-
你使用的是哪个版本的 react-hook-form?
-
react-hook-form 的版本是 7.22.2
-
你不需要用控制器包装所有这些离子组件,有些只需使用寄存器就可以正常工作 - stackblitz.com/edit/ionic-react-hook-form-me1pv4?file=src/…
标签: reactjs ionic-framework react-hook-form