我正在尝试将打字稿集成到我们的项目中,到目前为止,我偶然发现了样式组件库的一个问题
考虑这个组成部分
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个错误,本质上相同 <Icon source={src} width={width} height={height} />
<Icon source={src} width={width} height={height} />
输入{source:any; 宽度:字符串;不能分配给IntrinsicAttributes类型…类型{source:any;类型中缺少属性’onPress’ 宽度:字符串;高度:字符串;}
不能完全确定这是什么以及如何解决它,我是否需要以某种方式声明这些内容Icon?
Icon
编辑: 打字稿v2.6.1,样式化组件v2.2.3
据我所知,尚无官方方法(但?),但是您可以通过一些技巧来解决。首先,创建一个withProps.ts具有以下内容的文件:
withProps.ts
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文件内部,像这样使用它:
.tsx
// ... 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中为模板文字提供泛型的方法,但是我想目前这是您最好的选择。
归功于应得的信用:我从这里复制粘贴