尝试使用 Ionic React Hook Forms,谁能帮我解决以下问题
尝试动态构建表单,如何动态传递ion元素的属性。在下面的示例中,我想将 maxlength 和 text 属性(来自后端/formFields)传递给 IonInput 元素
如何将值预填充到输入字段
Form.tsx
import {
IonContent,
IonPage,
IonText,
IonButton,
} from "@ionic/react";
import React from "react";
import "./Form.css";
import { useForm } from "react-hook-form";
import * as globalStructre from "../Components/Content";
import Input from "../Components/Input";
import Date from "../Components/Date";
import Select from "../Components/Select";
import Textarea from "../Components/Textarea";
import Toggle from "../Components/Toggle";
const Form: React.FC = () => {
const { control, handleSubmit } = useForm();
const formFields: globalStructre.IngressProps[] = [
{
type: "Input",
name: "email",
component: ['type=\'email\''],
label: "Email",
value: "",
},
{
type: "Input",
name: "fullName",
component: ['maxlength = 60', 'type=\'text\''], //properties
label: "Full Name",
value: "test",
},
{
type: "Input",
name: "password",
component: ['maxlength = 12', 'type=\'password\''],
label: "Password",
value: "",
},
];
const registerUser = (data: any) => {
console.log("creating a new user account with: ", data);
};
const buildForm = (field: globalStructre.IngressProps, key: any) => {
let inputElement = null;
switch (field.type) {
case "Input":
inputElement = (
<Input
key={key}
name={field.name}
control={control}
component={field.component}
value={field.value}
label={field.label}
rules={field.rules}
/>
);
break;
}
return inputElement;
};
return (
<IonPage>
<IonContent>
<div className="ion-padding">
<IonText color="muted">
<h2>Create Account</h2>
</IonText>
<form onSubmit={handleSubmit(registerUser)}>
{formFields.map((field, index) =>
//<Input {...field} control={control} key={index} />
buildForm(field, index)
)}
<IonButton expand="block" type="submit" className="ion-margin-top">
Register
</IonButton>
</form>
</div>
</IonContent>
</IonPage>
);
};
export default Form;
输入.tsx
import React, { FC } from "react";
import { IonItem, IonLabel, IonInput, IonText } from "@ionic/react";
import { Controller} from "react-hook-form";
import * as globalStructre from './Content';
import './Input.css';
const Input: FC<globalStructre.IngressProps> = ({
key,
name,
control,
component,
value,
label,
rules,
errors,
}) => {
return (
<>
<IonItem >
{label && <IonLabel position="floating">{label}</IonLabel>}
<Controller
render = {({ onChange, onBlur, value }) => (
<IonInput
key={key}
value ={value}
onIonChange={onChange}
/>
)}
name={name}
control={control}
rules = {rules}
/>
</IonItem>
</>
);
};
export default Input;