簡體   English   中英

如何讓 React 項目中的 Emotion 樣式組件與 TypeScript 一起使用?

[英]How to get Emotion styled component in a React project to work with TypeScript?

我正在學習 TypeScript,並試圖將一個使用 Emotion 的小項目轉換為 TypeScript。

我陷入了以下幾點。

以下代碼

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

給出錯誤

TS2345:類型參數 '(props: Pick, HTMLDivElement>, "color" | "hidden" | "style" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | ... 247 more ... | "css" > & { ...; }) => { ...; }' 不能分配給 'TemplateStringsArray' 類型的參數。 輸入 '(props: Pick, HTMLDivElement>, "color" | "hidden" | "style" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | ... 247 more ... | "css"> & { . ..; }) => { ...; }' 缺少來自類型 'TemplateStringsArray' 的以下屬性:raw、concat、join、slice 等 18 個。 ⌥⇧⏎⌥⏎

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

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

到我的tsconfig.json編譯器選項,以及嘗試將道具的類型添加到樣式組件中,如下所示

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 與其他庫集成是非常不透明的。 我已經從項目中放棄了 PropTypes,即使它們提供了 TS 沒有的運行時檢查,因為讓它們與 TS 一起工作很棘手。

非常感謝任何幫助!

您可以使用:

interface StyleProps {
   color: string;
}    

export const Title = styled.div<StyleProps>`
   font-size: 20,
   color: ${color},
   font-weight: 700
`;

如果不需要重復使用,可以直接聲明類型。 我還發現解構 props 並使用模板文字可以更輕松地處理更長的 CSS 聲明。

export const Title = styled.div<{color: string}>(({color}) => `
    font-size: 20px;
    color: ${color};
    font-weight: 700;
`);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM