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

React+TypeScript向事件处理函数传变量报错求助

解决React表单提交时event未定义的错误

你的代码核心问题是表单onSubmit的箭头函数没有接收event参数,直接在回调里引用event变量会导致它未定义,TypeScript因此抛出“event已弃用且不可分配”的错误。

修正方案

只需要在箭头函数中显式接收event参数,再传递给处理函数即可:

type SearchFormProps = {
    styles: React.CSSProperties;
    classNames: string;
};

const onSubmitHandler=(event: React.SyntheticEvent, isSearched?:boolean)=>{
  event.preventDefault();
   const target = event.target as typeof event.target & {
      username: { value: string };
    };
  const username = target.username.value; 
  console.log(username, isSearched);
}

export const SearchForm=({classNames, styles}: SearchFormProps)=>{
  const SearchBoolean = useContext(SearchBooleanContext);
  const {isSearched, setIsSearched} = SearchBoolean;
  
  return (
    <div>
      {/* 关键修改:在箭头函数中接收event参数 */}
      <Form onSubmit={(event)=>onSubmitHandler(event, isSearched)}>
      <Form.Group className="mb-3" controlId="formBasicUsername">
        <Form.Control type="text" placeholder="Enter username" name="username" />
      </Form.Group>
      <Button variant="primary" type="submit" >
        Search
      </Button>
      </Form>
    </div>
   
  );
}

为什么这样能解决问题

React在触发onSubmit时会自动传入表单提交的SyntheticEvent对象,但你的原箭头函数没有接收这个参数,导致内部引用的event是未定义的变量。显式接收后,就能正确将事件对象传递给onSubmitHandler,正常执行preventDefault()和获取表单值的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 04:45:00