You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+TypeScript表单报错:找不到setTask及参数e隐式为any

React表单TypeScript报错修复方案

报错分析与解决

1. 错误:Cannot find name 'setTask'(第5行)

  • 直接原因:const拼写错误成了cosnt,导致useState的解构赋值失败,setTask未被正确声明。
  • 附带问题:useState初始值用了空对象{},但输入框的值是字符串类型,会导致输入渲染异常,需改为空字符串""。

2. 错误:Parameter 'e' implicitly has an 'any' type(第7行)

TypeScript要求函数参数必须显式指定类型:

  • 表单提交事件e的类型为React.FormEvent<HTMLFormElement>
  • 输入框onInput事件的e类型为React.ChangeEvent<HTMLInputElement>

修复后的完整代码

import React, { useState } from 'react';
import { PlusIcon } from '@heroicons/react/24/solid'

const CustomForm = () => {
    const [task, setTask] = useState("");

  const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    console.log(e);
  }

  return (
    <form 
      className="todo"
      onSubmit={handleFormSubmit}
    >
      <div className="wrapper">
        <input 
          type="text" 
          id="task"
          className="input"
          value={task}
          onInput={(e: React.ChangeEvent<HTMLInputElement>) => setTask(e.target.value)}
          required
          autoFocus
          maxLength={60}
          placeholder="Enter Task"
        />
        <label htmlFor="task" className="label">
          Enter Task
        </label>
      </div>   
      <button
        className="btn"
        aria-label="Add task"
        type="submit"
      >
        <PlusIcon />
      </button>
    </form>
  )
}

export default CustomForm

补充说明

  • 若未安装Heroicons,执行命令:npm install @heroicons/react
  • 确保项目已配置TypeScript环境,且安装了@types/react依赖

内容的提问来源于stack exchange,提问作者Akshay Bankapure

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:10:45