React styled-components中styled(Row)的TypeScript重载匹配错误修复求助
修复React中
styled(Row)的TypeScript类型错误 问题代码
import { Col, Row } from 'react-grid-system'; import styled from 'styled-components'; const HeaderWrapper = styled(Row)` margin: 10px 0; border-bottom: 1px solid; padding: 4px 0; `;
错误信息
No overload matches this call. Overload 1 of 2, '(component: AnyStyledComponent): ThemedStyledFunction<any, any, any, any>', gave the following error. Argument of type 'typeof Row' is not assignable to parameter of type 'AnyStyledComponent'. Type 'typeof Row' is not assignable to type 'StyledComponent<any, any, any, never>'. Type 'typeof Row' is not assignable to type 'string'. Overload 2 of 2, '(component: keyof IntrinsicElements | ComponentType<any>): ThemedStyledFunction<keyof IntrinsicElements | ComponentType<any>, any, {}, never>', gave the following error. Argument of type 'typeof Row' is not assignable to parameter of type 'keyof IntrinsicElements | ComponentType<any>'. Type 'typeof Row' is not assignable to type 'ComponentClass<any, any>'.
解决方案
安装/更新类型定义包
先确认是否安装了react-grid-system的TypeScript类型包,执行以下命令安装:npm install @types/react-grid-system --save-dev # 或使用yarn yarn add @types/react-grid-system -D安装完成后重启TypeScript服务,多数情况下类型不匹配的问题会直接解决。
类型断言强制兼容
若安装类型包后问题仍存在,可通过类型断言将Row强制转换为ComponentType:import { Col, Row } from 'react-grid-system'; import styled from 'styled-components'; import { ComponentType } from 'react'; const HeaderWrapper = styled(Row as ComponentType)` margin: 10px 0; border-bottom: 1px solid; padding: 4px 0; `;包裹式替代方案
如果以上两种方法都无效,可以将Row包裹在styled原生元素中(注意需手动继承Row原有样式):import { Col, Row } from 'react-grid-system'; import styled from 'styled-components'; const StyledWrapper = styled.div` margin: 10px 0; border-bottom: 1px solid; padding: 4px 0; `; const HeaderWrapper = (props) => ( <StyledWrapper> <Row {...props} /> </StyledWrapper> );
错误原因
该错误本质是TypeScript无法确认react-grid-system的Row组件类型符合styled-components要求的ComponentType规范,要么是缺失对应的类型定义,要么是组件本身的类型声明存在兼容性问题。
内容的提问来源于stack exchange,提问作者johnjavier
相关产品推荐
相关产品推荐

