最近,我们使用最新版本的样式组件6.0.8更新了针对RN072.5
的项目"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"
}
给定以下组件,打字稿将 source 和 resizeMode 识别为有效的 props
const BlurImage = styled.Image.attrs({
source: blur,
resizeMode: 'stretch'
})`
width: 100%;
height: 100%;
`;
但是当我尝试使用这些组件时,它给了我以下错误
Property source is missing in type {} but required in type
FastOmit<FastOmit<Substitute<ImageProps, ImageProps & RefAttributes<Image>>, never>, never>
等待“更好的解决方案”,如果您需要“使其尽快工作”,我将向您发布我的快速而肮脏的解决方法。
我只是输入“可选”我的默认属性。我需要将
styled-components
降级为 6.0.7
版本才能使其正常工作。
const BlurImage = styled(Image).attrs<{ source?: ImageSourcePropType | undefined }>({
source: blur,
resizeMode: 'stretch'
})`
width: 100%;
height: 100%;
`;
这样就可以使用
<BlurImage />
,而无需强制source
(错误输入)。 顺便说一句,这不是一个解决方案,因为具有许多属性的组件编写和输入起来会变得很长。而且,如果您忘记指定它,则在执行过程中会抛出错误,但在 TS 中不会。您也可以将其输入为
.attrs<Partial<ImageProps>>
,但这更加危险,因为隐藏了 all
强制道具。