reactjs - 在反应组件上出现“不可分配给类型”错误,我怎样才能更好地理解它?
问题描述
我正在构建这个组件来测试 react-spring 库。我在codesandbox上启动它,然后将它本地拉到我的电脑上。当我把它拉下来时,这个错误出现了,我不知道如何解释它或导致它的原因。我对打字稿很陌生,所以非常感谢任何帮助。
起初,我认为它可能是children
prop 的错误类型,但后来意识到它实际上是width
and 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)
解决方案
为了让 Typescript 知道您将要传递给样式化 div 的自定义道具,您需要使用如下类型参数让它知道:
interface StyledCardProps {
width?: number
height?: number
}
const StyledCard = styled.div<StyledCardProps>`
// your css here
`
推荐阅读
- multithreading - 为什么在另一个线程中循环大量数据会导致过度活跃的 GC,并阻止某些数据被释放?
- docker - 如何连接到运行 Server Core 的 Azure 容器实例
- vb.net - MSBuildWorkspace.Create 似乎在 VB 中无法正常工作
- jquery - 带有 Animate.css 的轮播滑动过渡
- python - 使用相同的键从 dict.values() 获取最大值
- javascript - 通过 Web3 访问智能合约成员函数
- angular - ng build 命令运行“找不到条目”后出错
- python - PIL 去除 draw.ellipse 绘制的绘图点周围的噪声
- unity3d - Photon matchmaking - 在 Unity 中使用 SQL 大厅加入或创建房间
- ios - 加载png图像时出错