TypeScript+React+Material UI使用Box组件报No overload matches this call错误
报错原因
你遇到的No overload matches this call错误和仓库配置无关,是TypeScript类型匹配的问题:MUI的Box组件默认的属性类型只包含通用容器属性,当你通过component参数指定其渲染为img元素时,TypeScript不会自动合并img的原生属性(alt、src等)到Box的属性类型中,因此会抛出类型不匹配的报错。
解决方案
方案1:显式声明
Box的泛型类型,指定要渲染的元素属性
该方案可以保留Box组件的所有能力,同时通过类型声明让TS识别img原生属性:// material import { Box } from '@material-ui/core'; import type { ImgHTMLAttributes } from 'react'; export default function Logo() { return ( <Box<ImgHTMLAttributes<HTMLImageElement>> component="img" alt="logo" src="/static/brand/logo.svg" height={40} /> ); }方案2:直接使用原生
img元素(更适合纯图片渲染场景)
如果你不需要用到Box的特殊布局能力,直接用原生img代码更简洁,样式可以用内联style或者MUI的sx属性实现:export default function Logo() { return ( <img alt="logo" src="/static/brand/logo.svg" style={{ height: 40 }} // 如需使用MUI的样式系统,替换style为sx即可: // sx={{ height: 40, marginX: 2 }} /> ); }方案3(仅适配MUI v4版本):通过
htmlAttributes参数传入原生img属性
如果你使用的是MUI v4版本,可以用Box内置的htmlAttributes字段传递底层原生元素的属性:// material import { Box } from '@material-ui/core'; export default function Logo() { return ( <Box component="img" height={40} htmlAttributes={{ alt: 'logo', src: '/static/brand/logo.svg' }} /> ); }
内容的提问来源于stack exchange,提问作者asier
相关产品推荐
相关产品推荐

