我正在使用typescript和react进行表单注册,但是,当我尝试提交handleSignup函数时,我遇到了一个键入错误。
import { useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { api } from "../../services/api";
export const Signup = () => {
const schema = yup.object().shape({
name: yup.string(),
email: yup.string(),
password: yup.string(),
address: yup.object().shape({
zipCode: yup.string(),
number: yup.number(),
complement: yup.string(),
})
})
interface signUpCredentials {
name: string
email: string
password: string
address: {
zipCode: string
number: number
complement: string
}
}
const {
register,
formState: { errors },
handleSubmit,
} = useForm({
resolver: yupResolver(schema)
})
const handleSignup = ({ address, email, name, password }: signUpCredentials ) => {
api
.post("/users/signup", { address, email, name, password })
.then((response) => {
console.log("Created")
})
.catch((err) => {
console.error("Not created")
})
}
return (
<form
onSubmit={handleSubmit(handleSignup)}
>
<input
{...register("name")}
placeholder="name"
/>
<input
{...register("email")}
placeholder="email"
/>
<input
{...register("password")}
placeholder="password"
/>
<input
{...register("address.zipCode")}
placeholder="zipCode"
/>
<input
{...register("address.number")}
placeholder="number"
/>
<input
{...register("address.complement")}
placeholder="complement"
/>
<button type="submit" >
Submit
</button>
</form>
)
}
我面临的问题正是 *
onSubmit = {处理提交(处理注册)}
我正在接收:
类型为"({地址、电子邮件、名称、密码}:signUpCredentials)=〉void "不能赋给类型为" SubmitHandler "的参数。参数" __0 "和" data "的类型不兼容。类型"{[ x:字符串]:任意; "}"缺少类型" signUpCredentials "的以下属性:名称、电子邮件、密码、地址(2345)
2条答案
按热度按时间6ie5vjzr1#
你还没有给
useForm
钩子指定类型变量signUpCredentials
,你应该把onSubmit
处理程序改为handleSignup
,并在里面调用handleSubmit
。为了更好地理解,我创建了一个Code Sandbox链接,其中删除了指向服务的
import
语句,因为我们没有该语句,您可以通过检查控制台看到调用函数时没有任何警告/错误。参考:React Hook form (TS)
fcwjkofz2#
不需要像@sri-vineeth提到的那样修改
onSubmit
,只需要使用SubmitHandler
类型即可。另外请注意接口和类型应该使用PascalCase。因此将
signUpCredentials
更改为SignUpCredentials
。