编辑不更新时的 react-hook-form
react-hook-form when editing doesn't update
我找不到一种方法来将数据库中的现有信息提供给 react-hook-form
库,以便在单击提交时重新验证并在数据更改时更新它。
问题是单击 submit
按钮时,此对象将显示 firstName
和 lastname
没有任何值:
{firstName: undefined, lastname: undefined}
我的组件的简化版本:
import React from "react";
import { useForm } from "react-hook-form";
import { TextField } from "@material-ui/core";
const App = (props) => {
const { register, handleSubmit} = useForm();
const onSubmit = (data) => {
console.log(data); // ---> here
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<h2>Step 1</h2>
<label>
First Name:
<TextField {...register("firstName")} defaultValue="firstname" />
</label>
<label>
Last Name:
<TextField {...register("lastname")} defaultValue="lastname" />
</label>
<input type="submit" />
</form>
);
};
export default App
知道如何创建允许您编辑字段的表单吗?
查看 codesandbox
问题出在 TextFiled
组件上。 register
设置不正确。
根据 MUI
documentation:
props:inputProps type:object description:Attributes applied to the input element.
所以你需要通过 register
抛出 inputProps
:
<TextField inputProps={register("firstName")} defaultValue="firstname" />
<TextField inputProps={register("lastname")} defaultValue="lastname" />
我找不到一种方法来将数据库中的现有信息提供给 react-hook-form
库,以便在单击提交时重新验证并在数据更改时更新它。
问题是单击 submit
按钮时,此对象将显示 firstName
和 lastname
没有任何值:
{firstName: undefined, lastname: undefined}
我的组件的简化版本:
import React from "react";
import { useForm } from "react-hook-form";
import { TextField } from "@material-ui/core";
const App = (props) => {
const { register, handleSubmit} = useForm();
const onSubmit = (data) => {
console.log(data); // ---> here
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<h2>Step 1</h2>
<label>
First Name:
<TextField {...register("firstName")} defaultValue="firstname" />
</label>
<label>
Last Name:
<TextField {...register("lastname")} defaultValue="lastname" />
</label>
<input type="submit" />
</form>
);
};
export default App
知道如何创建允许您编辑字段的表单吗?
查看 codesandbox
问题出在 TextFiled
组件上。 register
设置不正确。
根据 MUI
documentation:
props:inputProps type:object description:Attributes applied to the input element.
所以你需要通过 register
抛出 inputProps
:
<TextField inputProps={register("firstName")} defaultValue="firstname" />
<TextField inputProps={register("lastname")} defaultValue="lastname" />