首页 > 解决方案 > 如何使用 React 和 Typescript 使用情感/样式

问题描述

我已经包装了我的根组件,ThemeProvider从中@emotion/react可以访问props.theme

const StyledDiv = styled.div`
  background-color: ${(props) => props.theme.palette.primary.main};
`;

问题: props.theme根据 TS 是一个空对象 - paletteTheme 类型上不存在(但是我传递给主题提供者的对象确实包含该属性)。如果我让 TS 忽略这一点,则代码有效。

文档涵盖了这一点,这似乎是一个简单的解决方法: 扩展 Emotion 主题类型

但是,我对文档的理解不够好,无法使Theme类型props.theme具有正确的属性。

非常感谢任何为我指明正确方向的帮助!

标签: reactjstypescriptemotion

解决方案


添加此文件types.d.ts

import "@emotion/react";
import { IPalette } from "../your-palette";

declare module "@emotion/react" {
  export interface Theme extends IPalette {}
}

推荐阅读