typescript 我遇到了一个我不理解的样式化组件错误

x4shl7ld  于 2023-06-24  发布在  TypeScript
关注(0)|答案(1)|浏览(104)

我试图在React项目中使用ThemeContextuseContext中的变量,但我得到一个错误,说“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;
evrscar2

evrscar21#

您遇到的错误与TypeScript的类型检查有关。它告诉您'colors'属性在类型'DefaultTheme'上不存在|未定义发生此错误的原因是ThemeContext可能未定义。
要解决此问题,可以使用styled-components中的ThemeProvider组件向ThemeContext提供默认主题。以下是如何修改代码以修复错误:

import Switch from "react-switch";
import { Container, Icon } from "./Switcher.Style";
import { useContext } from "react";
import { ThemeContext, DefaultTheme } from "styled-components";

interface IProps {
  toggleTheme(): void;
}

const Switcher: React.FC<IProps> = ({ toggleTheme }) => {
  const theme = useContext<DefaultTheme>(ThemeContext);
  const { colors, title } = theme;

  const MoonIcon = () => {
    return <Icon>🌑</Icon>;
  };

  const SunIcon = () => {
    return <Icon>☀️</Icon>;
  };

  if (!theme) {
    // Handle the case when the theme is not available
    return null; // or display a loading state, error message, etc.
  }

  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;

相关问题