【发布时间】:2018-09-04 11:33:17
【问题描述】:
背景:
我正在使用 Typescript-React-styledComponents,
我正在尝试这个简单的案例,我通过父组件传递 size 属性,这将设置子组件的字体大小。
已编辑:
错误:
ts 向我抛出这个:
Property 'size' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<ThemedOuterStyledProps<DetailedHTMLProps...'.
问题:
我注意到
size可能是一个有问题的道具名称,因为我在其他道具上没有收到任何错误。你知道为什么吗?更一般的问题 - 我错过了什么?
代码:
父组件
<Parent>
<Child text="Red Bikini" color='red' size={2}/>
</Parent>
子组件
import * as React from 'react';
import styled from 'styled-components';
//EDITED
interface headerSizeType {
1: string;
2: string;
3: string;
4: string;
5: string;
6: string;
}
const size: headerSizeType = {
1: '2em',
2: '1.5em',
3: '1.17em',
4: '1em',
5: '.83em',
6: '.67em'
}
interface ChildProps {
text: string;
size?: number;
color?: string;
style?: any;
children?: React.ReactChildren;
className?: string;
}
const ChildStyle = styled.h2`
display: inline-block;
color: ${(props: any) => props.color || 'black'};
font-size: ${props => size[props.size] || 'black'}; //1st Error here
`;
const Child= (props: ChildProps): JSX.Element => {
console.log(props.color)
return (
<ChildStyle color={props.color} size={props.size}> //2nd Error here
{ props.text }
</ChildStyle>
);
};
export default Title;
【问题讨论】:
-
const size: any = {...}... 是什么让你写出这么糟糕的东西? -
@AluanHaddad 我是新人,所以你可能会在这里看到一些糟糕的东西 :) 我编辑了代码,很高兴听到有什么问题,以及正确的方法是什么
-
明白了。类型注释是可选的。写
const size = {...},语言会为你推断出一个丰富的、经过良好检查的类型。在那里使用any完全违背了语言的目的。
标签: reactjs typescript styled-components