问题描述
我正在尝试将 TypeScript 集成到我们的项目中,到目前为止我偶然发现了一个关于 styled-components 的问题 图书馆.
I'm trying to integrate TypeScript into our project and so far I stumbled upon one issue with styled-components library.
考虑这个组件
import * as React from "react";
import styled from "styled-components/native";
import { TouchableOpacity } from "react-native";
// -- types ----------------------------------------------------------------- //
export interface Props {
onPress: any;
src: any;
width: string;
height: string;
}
// -- styling --------------------------------------------------------------- //
const Icon = styled.Image`
width: ${(p: Props) => p.width};
height: ${(p: Props) => p.height};
`;
class TouchableIcon extends React.Component<Props> {
// -- default props ------------------------------------------------------- //
static defaultProps: Partial<Props> = {
src: null,
width: "20px",
height: "20px"
};
// -- render -------------------------------------------------------------- //
render() {
const { onPress, src, width, height } = this.props;
return (
<TouchableOpacity onPress={onPress}>
<Icon source={src} width={width} height={height} />
</TouchableOpacity>
);
}
}
export default TouchableIcon;
下面一行抛出 3 个错误,本质上是相同的
Following line throws 3 errors, that are same in nature <Icon source={src} width={width} height={height} />
输入 {source: any;宽度:字符串;高度:字符串;} 不可分配键入 IntrinsicAttributes ... 类型中缺少属性onPress"{来源:任何;宽度:字符串;高度:字符串;}
不完全确定这是什么以及如何修复它,我是否需要在 Icon
或类似的东西上声明这些?
Not entirely sure what this is and how to fix it, do I somehow need to declare these on Icon
or something of this sort?
typescript v2.6.1
, styled-components v2.2.3
typescript v2.6.1
, styled-components v2.2.3
推荐答案
这个答案已经过时了,最新的答案在这里:https://stackoverflow.com/a/52045733/1053772
据我所知,目前还没有正式的方法(还没有?)来做到这一点,但你可以通过一些技巧来解决它.首先,创建一个 withProps.ts
文件,内容如下:
As far as I can tell there is no official way (yet?) to do this, but you can solve it with a bit of trickery. First, create a withProps.ts
file with the following content:
import * as React from 'react'
import { ThemedStyledFunction } from 'styled-components'
const withProps = <U>() => <P, T, O>(fn: ThemedStyledFunction<P, T, O>) =>
fn as ThemedStyledFunction<P & U, T, O & U>
export { withProps }
现在,在您的 .tsx
文件中,像这样使用它:
Now, inside your .tsx
files, use it like this:
// ... your other imports
import { withProps } from './withProps'
export interface IconProps {
onPress: any;
src: any;
width: string;
height: string;
}
const Icon = withProps<IconProps>()(styled.Image)`
width: ${(p: IconProps) => p.width};
height: ${(p: IconProps) => p.height};
`;
你应该很高兴去.这绝对不理想,希望很快就会有一种方法可以在 TS 中为模板文字提供泛型,但我想现在这是您最好的选择.
And you should be good to go. It's definitely not ideal and hopefully there will be a way to provide generics to template literals soon in TS, but I guess that for now this is your best option.
信用是在信用到期的地方给出的:我从这里复制粘贴了这个
Credit is given where credit is due: I copypasted this from here
这篇关于使用带有 props 和 TypeScript 的样式组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!