首页 > 解决方案 > 在反应组件上出现“不可分配给类型”错误,我怎样才能更好地理解它?

问题描述

我正在构建这个组件来测试 react-spring 库。我在codesandbox上启动它,然后将它本地拉到我的电脑上。当我把它拉下来时,这个错误出现了,我不知道如何解释它或导致它的原因。我对打字稿很陌生,所以非常感谢任何帮助。

起初,我认为它可能是childrenprop 的错误类型,但后来意识到它实际上是widthand height,现在我不确定它是否是 a styled-components(因为错误出现在 下StyledCard)或者当你使用 children 渲染 prop 方法时,你必须指定你的类型不一样。。

import * as React from "react"
import styled from "styled-components"

const StyledCard = styled.div`
  width: ${(props: any) => props.width}px;
  height: ${(props: any) => props.height}px;
  box-shadow: 0px 2px 4px -1px rgba(0, 0, 0, 0.2),
    0px 4px 5px 0px rgba(0, 0, 0, 0.14), 0px 1px 10px 0px rgba(0, 0, 0, 0.12);
  text-align: center;
`

interface ICardProps {
  children?: React.ReactNode
  width?: number
  height?: number
}

const Card: React.FC<ICardProps> = ({ width, height, children }) => {
  return (
    <StyledCard width={width} height={height}>
      {children}
    </StyledCard>
  )
}

export default Card

这是我得到的错误:

Type '{ children: ReactNode; width: number | undefined; height: number | undefined; }' is not assignable to type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "style" | "title" | "key" | "defaultChecked" | "defaultValue" | ... 246 more ... | "onTransitionEndCapture"> & { ...; }, "style" | ... 251 more ... | "onTransitionEndCapture"> & Partial<...>, "style" | ... 251 mor...'.
  Property 'width' does not exist on type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "style" | "title" | "key" | "defaultChecked" | "defaultValue" | ... 246 more ... | "onTransitionEndCapture"> & { ...; }, "style" | ... 251 more ... | "onTransitionEndCapture"> & Partial<...>, "style" | ... 251 mor...'.ts(2322)

标签: reactjstypescriptstyled-componentsreact-propstsx

解决方案


为了让 Typescript 知道您将要传递给样式化 div 的自定义道具,您需要使用如下类型参数让它知道:

interface StyledCardProps {
    width?: number
    height?: number
}

const StyledCard = styled.div<StyledCardProps>`
    // your css here
`

推荐阅读