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

MUI中Styled Box指定为form组件时onSubmit类型错误求解

MUI Styled组件指定component为form时onSubmit的类型解决方案

问题描述

将MUI代码通过styled()抽离为独立Styled组件后,出现TypeScript类型错误:

Type '(event: FormEvent) => void' is not assignable to type 'FormEventHandler'.
Types of parameters 'event' and 'event' are incompatible.
Type 'FormEvent' is not assignable to type 'FormEvent'.
Type 'HTMLDivElement' is missing the following properties from type 'HTMLFormElement': acceptCharset, action, autocomplete, elements, and 15 more.ts(2322)

代码示例:

// Mui styled component 
import { Box, BoxProps } from '@mui/material';
import { styled } from '@mui/material/styles';

export const StyledEntryBox = styled(Box)<BoxProps>(({ theme }) => ({
  // custom style 
}));

// Handler
import { FormEvent } from 'react';
const handleSubmit = (event: FormEvent<HTMLFormElement>): void => {}

// My component (box/form)
<StyledEntryBox component='form' boxShadow={3} onSubmit={handleSubmit}>
</StyledEntryBox>

问题原因

StyledEntryBox的泛型参数使用了默认的BoxProps,而BoxProps默认关联的是HTMLDivElement类型。即使通过component="form"将渲染元素改为form,TypeScript仍会沿用BoxProps的默认元素类型进行类型检查,导致事件类型不匹配。

正确解决方案

方案1:为Styled组件指定正确的Props类型

合并BoxProps与form元素的属性,让组件Props适配form元素:

import { Box, BoxProps } from '@mui/material';
import { styled } from '@mui/material/styles';
import { FormHTMLAttributes, FormEvent } from 'react';

// 组合Box的属性和form元素的属性
type StyledEntryBoxProps = BoxProps & FormHTMLAttributes<HTMLFormElement>;

export const StyledEntryBox = styled(Box)<StyledEntryBoxProps>(({ theme }) => ({
  // custom style 
}));

// 此时handleSubmit的类型可以正常匹配
const handleSubmit = (event: FormEvent<HTMLFormElement>): void => {
  // 逻辑代码
};

方案2:调整handleSubmit的事件类型(不推荐)

若不想修改Styled组件的泛型,可临时调整事件类型,同时通过类型断言获取正确的form元素:

const handleSubmit = (event: FormEvent<HTMLDivElement>): void => {
  // 将当前目标断言为HTMLFormElement
  const formElement = event.currentTarget as HTMLFormElement;
  // 后续基于formElement进行操作
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:22:43