我正在尝试使用 提交表单react hook forms。提交后我想清除所有字段。我读过有关使用reset(). 但它不起作用
import React, { Fragment } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as Yup from "yup";
import "react-toastify/dist/ReactToastify.css";
import {
Paper,
Box,
Grid,
TextField,
Typography,
Button,
} from "@material-ui/core";
export default function ResetPassword() {
const validationSchema = Yup.object().shape({
old_password: Yup.string().required("Password is required"),
new_password1: Yup.string().required("Password is required"),
new_password2: Yup.string().required("Password is required"),
});
const { register, handleSubmit, reset } = useForm({
resolver: yupResolver(validationSchema),
}); …Run Code Online (Sandbox Code Playgroud) 我第一次使用react-hook-form。我正在阅读文档并遵循。同样,我已经布置了组件并设计了它们的样式。现在我试图在表单提交后提醒数据。
这是ContactForm
import React, { useState } from 'react';
import * as S from './style';
import { PrimaryButton } from '@element/Button';
import TextInput from '@element/TextInput';
import { useForm } from 'react-hook-form';
export const ContactForm = () => {
const { register, handleSubmit } = useForm();
const [firstName, setFirstName] = useState('');
const onSubmit = (data) => {
alert(JSON.stringify(data));
};
return (
<S.ContactFormWrapper onSubmit={handleSubmit(onSubmit)}>
<TextInput
name={'firstName'}
label={'First Name'}
state={firstName}
setState={setFirstName}
placeholder={'John'}
type={'text'}
width={'48%'}
options={{
maxLength: '20',
minLength: '2',
required: true,
}} …Run Code Online (Sandbox Code Playgroud) 我有一些可清除的选择,我想将applets状态字段重置为空数组。
const defaultFormValues = { device: { ...initialDevice }, applets: [] };
const { control, getValues, setValue, reset, handleSubmit } = useForm<CreateDeviceFormData>({
mode: "all",
reValidateMode: "onChange",
defaultValues: defaultFormValues,
resolver: yupResolver(validationSchema),
});
const onChangeHandler = React.useCallback(
(value: Experience | null) => {
if (value) {
setValue("applets", getApplets(value));
} else {
setValue("applets", []);
// reset(defaultFormValues);
}
setValue("device.experience_id", value ? value.id : undefined);
},
[templateSelector, setValue],
);
console.log("current data", getValues(), control);
return (
<>
<SomeAutocompleteComponent control={control} onChange={onChangeHandler} />
<SelectAppletsComponent control={control} /> …Run Code Online (Sandbox Code Playgroud) 最近我正在努力创建 yup 模式。因为我正在这样做,所以我发现该方法when()完全不适合我,就像文档所说的和我在互联网上找到的其他解决方案一样。当我的复选框被选中时,true架构上的所有字段都应该是required,但他们没有。正如我的示例所示,我尝试了三种方法,但没有一种有效。也许有人知道我做错了什么?
我的测试代码是:
import "./styles.css";
import * as yup from "yup";
import { FormProvider, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import React, { useEffect } from "react";
export default function App() {
const schema = yup.object({
isRequired: yup.bool(),
firstName: yup.string().when("isRequired", (_, schema) => {
return schema.required();
}),
lastName: yup.string().when("isRequired", () => {
return yup.string().required();
}),
contact: yup.string().when("isRequired", {
is: true,
then: yup.string().required("Required")
})
});
const methods = useForm({
mode: …Run Code Online (Sandbox Code Playgroud) 我正在使用react-hook-form来构建一个表单。该表格运行良好,但测试未通过。
react-hook-form当我不使用并通过 onSubmit时测试通过<form onSubmit={onSubmit}>。当我通过 handleSubmit 传递 onSubmit 时<form onSubmit={handleSubmit(onSubmit)}>,它没有通过。
这是我的表格
App.js
import { useForm } from "react-hook-form";
export default function App({ onSubmit = (data) => console.log(data) }) {
const { handleSubmit, register } = useForm();
return (
// <form onSubmit={onSubmit}> <--- This works
// <form onSubmit={handleSubmit(onSubmit)}> <--- This doesn't work
<form onSubmit={handleSubmit(onSubmit)}>
<input
placeholder="Email"
defaultValue=""
key="email"
{...register("email")}
/>
<input
placeholder="Password"
defaultValue=""
key="password"
{...register("password")}
/>
<input type="submit" value="submit" />
</form>
);
}
Run Code Online (Sandbox Code Playgroud)
这是我为其编写的测试
App.test.js
import { …Run Code Online (Sandbox Code Playgroud) javascript reactjs react-testing-library react-hooks react-hook-form
我正在使用 Material UI 的自动完成多个 TextField、React Hook Form 和 Yup 来验证表单输入。
当我对 daysOfWeek 使用 Yup.string() 时,即使我选择了值,它也会显示错误消息。但是,如果我将其更改为 Yup.array(),则会显示以下错误...
daysOfWeek 必须是一个
array类型,但最终值是:(null从 value 转换"")。如果“null”旨在作为空值,请务必将架构标记为.nullable()
有没有办法使用 Yup 来验证 Material UI 的自动完成多个 TextField?先感谢您!
这是我的相关代码...
const [selected, setSelected] = useState([]);
const validationSchema = Yup.object().shape({
daysOfWeek: Yup.string()
.required("Days of the week are required")
});
const {
formState: {errors},
handleSubmit,
register
} = useForm({
resolver: yupResolver(validationSchema)
});
<Autocomplete
disableClearable
disablePortal
filterSelectedOptions
multiple
getOptionDisabled={(option) => option.disabled ? true : false}
getOptionLabel={(option) => option.label} …Run Code Online (Sandbox Code Playgroud) 具有以下组件:
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';
import * as yup from 'yup';
import { useToggle } from '../shared/hooks';
import {
SubsectionLayout,
Footer,
Textarea,
Input,
Modal,
Button
} from '../shared/ui-components';
const schema = yup.object().shape({
name: yup.string().required(),
description: yup.string().required()
});
export interface ITask {
name: string;
description: string;
}
export function MainComponent() {
const [isOpened, toggleModal] = useToggle(false);
const { handleSubmit, register, reset } = useForm({
resolver: yupResolver(schema)
});
const onSubmit = (data: ITask) => …Run Code Online (Sandbox Code Playgroud) 我将 Autocopmlete 组件的 defaultValue 设置如下:
<Controller
control={control}
name={name}
render={({field: {onChange, value}}) => (
<Autocomplete
freeSolo={freeSolo}
options={options}
renderInput={params => {
return <TextField {...params} label={label} margin="normal" variant="outlined" onChange={onChange} />
}}
onChange={(event, values, reason) => onChange(values)}
defaultValue={defaultValue}
/>
)}
/>
Run Code Online (Sandbox Code Playgroud)
该值基于defaultValue很好地显示。但是,当我单击提交按钮时,如果我不使用自动完成组件,则自动完成字段的值始终未定义。这是我注册钩子和组件的方法(简化代码)
const customerSchema = yup.object().shape({
route: yup.string().nullable()
})
const {control, handleSubmit} = useForm({
resolver: yupResolver(customerSchema)
})
const onSubmit = formData => {
console.log(formData) // autocomplete is undefined if no action on the autocomplete
}
<form noValidate autoComplete="off" onSubmit={handleSubmit(onSubmit)}>
<AutoCompleteInput
control={control}
name="route"
label="route"
options={customers_routes.map(option …Run Code Online (Sandbox Code Playgroud) I want to get the value of a field inside a react-hook-form component and print it outside the form. The value should be updated onChange. is there a way to use the useWatch outside the form component?
import React from "react";
import ReactDOM from "react-dom";
import { useForm, useWatch } from "react-hook-form";
import "./styles.css";
function Form() {
const { register, control, handleSubmit } = useForm();
return (
<>
<form onSubmit={handleSubmit((data) => console.log("data", data))}>
<label>Name:</label>
<input ref={register} name="name" />
<p>{useWatch({ control, …Run Code Online (Sandbox Code Playgroud) 我有以下用例:
\n用户想要切换配置文件是否处于活动状态。
\n配置: \nNext.js、\nFauna DB、\nreact-hook-form
\n我使用 useState 来更改切换上的状态,并使用 React-hook-forms 将其他值发送到我的 Fauna 数据库以及切换中的状态。我希望切换具有数据库中的状态,当用户切换它并按下提交按钮时,我想更改数据库中的状态。
\n当我切换数据库时,我似乎无法将正确的状态发送回数据库。
\n主要成分:
\nexport default function Component() {\n const [status, setStatus] = useState(\n userData?.profileStatus ? userData.profileStatus : false\n );\n\nconst defaultValues = {\n profileStatus: status ? userData?.profileStatus : false\n };\n\nconst { register, handleSubmit } = useForm({ defaultValues });\n\n const handleUpdateUser = async (data) => {\n\n const {\n profileStatus\n } = data;\n try {\n await fetch(\'/api/updateProfile\', {\n method: \'PUT\',\n body: JSON.stringify({\n profileStatus\n }),\n headers: {\n …Run Code Online (Sandbox Code Playgroud) react-hook-form ×10
reactjs ×8
react-hooks ×4
javascript ×3
material-ui ×3
next.js ×3
yup ×2
faunadb ×1
forms ×1
frontend ×1
react-redux ×1
schema ×1
typescript ×1
use-state ×1
validation ×1