Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 自定义useForm类型脚本无法正常工作_Reactjs_Typescript_React Hooks_Tsx - Fatal编程技术网

Reactjs 自定义useForm类型脚本无法正常工作

Reactjs 自定义useForm类型脚本无法正常工作,reactjs,typescript,react-hooks,tsx,Reactjs,Typescript,React Hooks,Tsx,下面是我的useFormhook: const useForm = () => { const [state, setState] = useState({}); const inputHandler: (e: React.ChangeEvent<HTMLInputElement>) => void = ( e: React.ChangeEvent<HTMLInputElement> ) => { e.persist();

下面是我的
useForm
hook:

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;
const useForm=()=>{
const[state,setState]=useState({});
权限管理器中的常量:(e:React.ChangeEvent)=>void=(
e:React.change事件
) => {
e、 坚持();
设置状态((预状态)=>({
…预先声明,
[e.target.name]:e.target.value,
}));
};
返回[状态,inputHandler];
};
导出默认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"
        />
const[state,inputHandler]=useForm();
...

但是
onChange
总是抱怨类型
{}
不可分配给类型
changeenthandler
。我已将
{}
更改为
Any
,但inputHandler似乎总是返回我在自定义挂钩中定义的init state而不是事件处理程序函数。

经过几个小时的调查,我发现错误是由返回[]引起的。我用return{…}替换它。钩子工作起来很有魅力

谢谢你的回复,我发现错误是由返回数组引起的。