使用样式化组件和TypeScript

时间:2020-04-02 08:32:38

标签: reactjs typescript styled-components

创建一个组件库,我想将布局组件直接包含在库中。为此,我刚刚创建了经典组件(ContainerRowCol),它实际上只是库react-grid-system中的经典组件的副本。

例如,我的组件Col如下所示:

import React from 'react'
import styled from 'styled-components'
import { Col as ReactGridSystemCol, ColProps } from 'react-grid-system';

// C O M P O N E N T
const Col: React.FunctionComponent<ColProps> = (props) => {
  const { children } = props

  return (
    <StyledCol {...props}>
      {children}
    </StyledCol>
  )
}

// S T Y L E S
const StyledCol = styled<ColProps>(ReactGridSystemCol)` // <- Type 'ColProps' does not satisfy the constraint '"symbol" | "object" ...
  /* ... */
`

StyledCol.displayName = 'StyledCol'

export default Col

从逻辑上讲,我说我的StyledCol组件继承自ReactGridSystemCol组件,因此我将能够为其添加样式并将其呈现在我的jsx中。

然后,我必须管理Col组件可以接收的道具。它们与ReactGridSystemCol完全相同,因此我使用的是库类型ColProps

然后,我指示StyledCol可以使用styled<ColProps>(ReactGridSystemCol)接收此道具。

问题在于明显存在类型错误,因为打字稿返回了此错误:

Type 'ColProps' does not satisfy the constraint '"symbol" | "object" | "a" | "abbr" | "address" | "area" | "article" | "aside" | "audio" | "b" | "base" | "bdi" | "bdo" | "big" | "blockquote" | "body" | "br" | "button" | "canvas" | ... 157 more ... | FunctionComponent<...>'.
  Type 'ColProps' is not assignable to type 'FunctionComponent<any>'.
    Type 'ClassAttributes<HTMLDivElement> & HTMLAttributes<HTMLDivElement> & { width?: string | number | undefined; ... 5 more ...; component?: (() => string) | undefined; } & Partial<...>' provides no match for the signature '(props: any, context?: any): ReactElement<any, any> | null'.

我在这里不太了解我的错误,因此,如果您有任何想法,我将非常感激。

1 个答案:

答案 0 :(得分:1)

尝试这样的事情。

def f(x): 
    return [x,x*x]

argument_list = list(range(1,8)) # random arguments
result_list = []
for a in argument_list:
    result_list += f(a)
print(result_list)