React Native中styled-components attrs方法无法继承Props问题
解决RN072.5 + styled-components 6.x中Image组件attrs默认Props的TypeScript类型错误
项目环境
项目升级至React Native 0.72.5,同时使用styled-components 6.0.8,核心依赖配置如下:
"dependencies": { ..., "react": "18.2.0", "react-is": "18.2.0", "react-native": "0.72.5", "styled-components": "6.0.7", "stylis": "^4.0.0" }, "devDependencies": { ..., "@types/react": "^18.0.24", "@typescript-eslint/eslint-plugin": "^5.54.1", "@typescript-eslint/parser": "^5.54.1", "@typescript-eslint/typescript-estree": "^5.54.1", "babel-plugin-styled-components": "^2.1.4", }, "resolutions": { "styled-components": "^6" }
组件定义
我们通过styled.Image.attrs为Image组件设置了默认的source和resizeMode:
const BlurImage = styled.Image.attrs({ source: blur, resizeMode: 'stretch' })` width: 100%; height: 100%; `;
错误现象
使用BlurImage组件时,TypeScript抛出类型错误:
Property 'source' is missing in type '{}' but required in type 'FastOmit<FastOmit<Substitute<ImageProps, ImageProps & RefAttributes
>, never>, never>'
解决方案
方案1:手动调整组件属性类型
通过TypeScript工具类型,将已设置默认值的source和resizeMode标记为可选,确保TypeScript识别这些属性无需手动传入:
import styled from 'styled-components/native'; import { ImageProps } from 'react-native'; // 剔除原ImageProps中的source和resizeMode,再将它们设为可选类型合并 type BlurImageProps = Omit<ImageProps, 'source' | 'resizeMode'> & Partial<Pick<ImageProps, 'source' | 'resizeMode'>>; const BlurImage = styled.Image.attrs<BlurImageProps>({ source: blur, resizeMode: 'stretch' })` width: 100%; height: 100%; `;
方案2:使用defaultProps设置默认值
改用组件的defaultProps来定义默认属性,这种写法能让TypeScript自动识别必填属性已被填充:
import styled from 'styled-components/native'; const BlurImage = styled.Image` width: 100%; height: 100%; `; BlurImage.defaultProps = { source: blur, resizeMode: 'stretch' };
方案3:确保类型依赖版本匹配
检查并升级@types/styled-components至适配v6的版本(需^5.1.26以上,建议安装最新版),避免类型定义不兼容导致的问题:
# npm npm install @types/styled-components@latest --save-dev # yarn yarn add @types/styled-components@latest --dev
原因说明
styled-components 6.x对TypeScript类型推导逻辑做了调整,attrs中设置的默认属性不会自动将原组件的必填属性转为可选,因此需要通过手动调整类型、改用defaultProps或升级类型依赖来解决。
内容的提问来源于stack exchange,提问作者Oltion Abazi
相关产品推荐
相关产品推荐

