【发布时间】:2021-07-19 00:30:52
【问题描述】:
下面是我的useForm钩子:
const useForm = () => {
const [state, setState] = useState({});
const inputHandler: (e: React.ChangeEvent<HTMLInputElement>) => void = (
e: React.ChangeEvent<HTMLInputElement>
) => {
e.persist();
setState((preState) => ({
...preState,
[e.target.name]: e.target.value,
}));
};
return [state, inputHandler];
};
export default useForm;
然后在 tsx 文件中我有代码:
const [state, inputHandler] = useForm();
...
<input
name="title"
type="text"
value={"title" in state ? state.title : ""}
onChange={inputHandler} // error!!!
placeholder="Title"
className="mb-2 focus:ring-red-500 focus:border-red-500 block w-full pr-12 sm:text-sm border-red-300 rounded-md"
/>
但是onChange 总是抱怨类型{} 不能分配给类型ChangeEventHandler<HTMLInputElement>。我已将 {} 更改为 Any 但似乎 inputHandler 总是返回初始化状态而不是我在自定义挂钩中定义的事件处理函数。
【问题讨论】:
-
感谢您的回复,我发现错误是由返回数组引起的。
标签: reactjs typescript react-hooks tsx