我试图在React项目中使用ThemeContext
的useContext
中的变量,但我得到一个错误,说“The 'colors' property doesnexist on type 'DefaultTheme”。|未定义”。
我已经创建了一个包含这些数据的style.d.ts
定义文件,但我仍然得到相同的错误。我在.tsx
中的类如下:
import Switch from "react-switch";
import { Container, Icon } from "./Switcher.Style";
import { useContext } from "react";
import { ThemeContext } from "styled-components";
interface IProps {
toggleTheme(): void;
}
const Switcher: React.FC<IProps> = ({ toggleTheme }) => {
const { colors, title } = useContext(ThemeContext);
const MoonIcon = () => {
return <Icon>🌑</Icon>;
};
const SunIcon = () => {
return <Icon>☀️</Icon>;
};
return (
<Container>
<Switch
onChange={toggleTheme}
checked={title === "light"}
height={20}
width={40}
checkedIcon={false}
uncheckedIcon={false}
handleDiameter={20}
offColor={colors.secondary}
onColor={colors.primary}
uncheckedHandleIcon={<MoonIcon />}
checkedHandleIcon={<SunIcon />}
/>
</Container>
);
};
export default Switcher;
1条答案
按热度按时间evrscar21#
您遇到的错误与TypeScript的类型检查有关。它告诉您'colors'属性在类型'DefaultTheme'上不存在|未定义发生此错误的原因是ThemeContext可能未定义。
要解决此问题,可以使用styled-components中的ThemeProvider组件向ThemeContext提供默认主题。以下是如何修改代码以修复错误: