【发布时间】:2020-10-18 10:45:06
【问题描述】:
我正在尝试使用自定义钩子管理表单,所以我有这个代码
FormHook.tsx:
import { useState } from 'react';
interface ICampos {
name: string;
email: string;
password: string;
}
const useForm = (initialState: ICampos) => {
const [values, setValues] = useState(initialState);
const handleInputChange = ({ target }: any) => {
setValues({
...values,
[target.name]: target.value
})
};
return [values, handleInputChange];
}
export default useForm
FormWithCustomHook.tsx:
import React from 'react'
import './effects.css'
import useForm from '../../hooks/useForm';
interface ICampos {
name: string;
email: string;
password: string;
}
const FormWithCustomHook = () => {
const [formValues, handleInputChange] = useForm({
name: '',
email: '',
password: ''
});
const { name, email, password } = formValues;
return (
<>
<h1> FormWithCustomHook </h1>
<hr />
<div className="form-group">
<input
type="text"
name="name"
className="form-control"
placeholder="Tu nombre"
autoComplete="off"
value={name}
onChange={handleInputChange} />
</div>
<div className="form-group">
<input
type="email"
name="email"
className="form-control"
placeholder="email@ejemplo.com"
autoComplete="off"
value={email}
onChange={handleInputChange} />
</div>
<div className="form-group">
<input
type="password"
name="password"
className="form-control"
placeholder="*****"
autoComplete="off"
value={password}
onChange={handleInputChange} />
</div>
</>
)
}
export default FormWithCustomHook;
我在 FormWithCustomHook.tsx 行遇到了这个错误:
const { name, email, password } = formValues;
它只在电子邮件和密码上标记错误:
“ICampos | 类型”上不存在“属性“电子邮件” (({ target }: any) => void)'.ts(2339)'
在我的 onChange 里面的输入说:
键入'ICampos | (({ target }: any) => void)' 不能分配给类型 '((event: ChangeEvent) => void) |不明确的'。
类型“ICampos”不可分配给类型“(事件:ChangeEvent)=> void”。
类型“ICampos”不匹配签名“(事件:ChangeEvent):void”.ts(2322)
index.d.ts(2092, 9):预期类型来自属性“onChange”,该属性在此处声明为类型“DetailedHTMLProps
我尝试在 customhook.tsx 上添加类型,但我真的不明白这个错误
【问题讨论】:
-
我已经更新了我的答案,显示了一个输入数组的解决方案。
标签: reactjs typescript react-hooks