【问题标题】:styled-components with Typescript throws me unknow errors when passing props使用 Typescript 的 styled-components 在传递道具时会引发未知错误
【发布时间】:2018-09-04 11:33:17
【问题描述】:

背景:

我正在使用 Typescript-React-styledComponents

我正在尝试这个简单的案例,我通过父组件传递 size 属性,这将设置子组件的字体大小。

已编辑:

错误:

ts 向我抛出这个:

Property 'size' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<ThemedOuterStyledProps<DetailedHTMLProps...'.

问题:

  1. 我注意到size 可能是一个有问题的道具名称,因为我在其他道具上没有收到任何错误。你知道为什么吗?

  2. 更一般的问题 - 我错过了什么?

代码:

父组件

<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


【解决方案1】:

我找到了解决方案,虽然我没有完全理解这个问题:)

但我通过将 styled-component 转换为 any 来临时修复它,如下所示:

const ChildStyle = styled.h2`
    display: inline-block;
    color: ${(props: any): string => props.color || 'black'};
    font-size: ${(props:any): any => headerSizes[props.size] || 'black'};
` as any;

我知道强制转换任何类型都不是好的做法,这就是为什么它是一个临时解决方案。

我听说 styled-component 中有一个 Theme Object,它为您提供了一个更漂亮、更干净的解决方案。

已编辑:

样式化组件类型的另一种解决方案:

https://github.com/jacob-ebey/styled-components-ts

【讨论】:

    【解决方案2】:

    您应该像这样为样式化组件指定道具类型:

    type MyStyledProps = {
        color?: string;
        size?: string;
    }
    
    const ChildStyle = styled.h2<StyledComponent<'h2', any, MyStyledProps, never>>`
        display: inline-block;
        color: ${(props) => props.color || 'black'};
        font-size: ${props => size[props.size] || 'black'};
    `;
    

    那么你的错误应该消失了。

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 2019-10-07
      • 2020-03-02
      • 2021-08-04
      • 1970-01-01
      • 2018-12-01
      相关资源
      最近更新 更多