如何在React项目中获得Emotion样式的组件以使用TypeScript?

问题描述 投票:2回答:1

我正在学习TypeScript,并试图将一个使用Emotion的小项目转换为TypeScript。

我在以下几点上遇到了困扰。

以下代码

export const Title = styled.div(props => ({
    fontSize: "20px",
    color: props.color,
    fontWeight: "700"
}));

给出错误

TS2345:类型为'(props:挑,HTMLDivElement>,“颜色” | “隐藏” | “样式” | “ defaultChecked” |“ defaultValue” | “ suppressContentEditableWarning” | ... 247更多... |“ css”>&{...; })=> {...; }'不能分配给类型的参数'TemplateStringsArray'。输入'(props:挑,HTMLDivElement>,“颜色” | “隐藏” | “样式” | “ defaultChecked” |“ defaultValue” | “ suppressContentEditableWarning” | ... 247更多... |“ css”>&{...; })=> {...; }'缺少以下属性从类型'TemplateStringsArray'中:raw,concat,join,slice和18更多。 ⌥⇧⏎⌥⏎

我做了一些谷歌搜索并添加了

   "types": ["@emotion/core","@emotion/styled"],                           /* Type declaration files to be included in compilation. */

到我的tsconfig.json中的编译器选项中,以及尝试将props的类型添加到这样的样式化组件中

type StyleProps = {
    [k: string]: string | undefined;
}
export const Title = styled.div<StyleProps>(props => ({
    fontSize: "20px",
    color: props.color,
    fontWeight: "700"
}));

那没用。

有趣的是,似乎只有这条线

    fontWeight: "700"

这就是这里的问题。以下工作正常

export const Container = styled.div(props => ({
    backgroundColor: props.color,
    padding: "20px",
    borderRadius: "14px",
    marginBottom: "20px",
    border: "1px solid rgba(100,100,50,0.5)",

}));

但是在其他字段上加了点空白。使Emotion与TS一起工作需要做什么?而且,同样重要的是,这里发生了什么?

我以前使用过类型化语言,但是感觉将TypeScript与其他库集成在一起非常不透明。我已经从项目中放弃了PropType,即使它们提供了TS不能提供的运行时检查,因为让它们与TS一起使用非常棘手。

任何帮助,不胜感激!

javascript reactjs typescript emotion
1个回答
0
投票

您可以使用:

interface StyleProps {
   color: string;
}    

export const Title = styled.div<StyleProps>`
   font-size: 20,
   color: ${color},
   font-weight: 700
`;
© www.soinside.com 2019 - 2024. All rights reserved.