具有Typescript和主题提供程序的样式组件,什么是正确的类型??

gj3fmq9x  于 2023-08-08  发布在  TypeScript
关注(0)|答案(4)|浏览(104)

在使用StyledComponents和ThemeProvider时,我在获取正确的类型时遇到了问题。
我尝试过这种方法:https://github.com/styled-components/styled-components/issues/1589
到目前为止我的代码:
App.tsx

import * as React from "react";
import "./styles.css";
import theme from "./theme";
import { ThemeProvider } from "styled-components";
import StyledButton from "./StyledButton";

export default function App() {
  return (
    <ThemeProvider theme={theme}>
      <div className="App">
        <StyledButton variant="primary">MyButton</StyledButton>
      </div>
    </ThemeProvider>
  );
}

字符串
theme.ts

import "styled-components";
const theme = {
  borderRadius: "0.7rem",
  color: "yellow"
};

export default theme;


StyledButton.tsx

import styled from "styled-components";

interface IButtonProps {
  color: string;
  backgroundColor: string;
  borderRadius?: string;
}

const buttonProps = (props: any): IButtonProps => {
  /* defaultValues / primary */
  let bp: IButtonProps = {
    color: props.theme.color,
    backgroundColor: "#2862c3c4"
  };

  if (props.variant === "primary") {
    return bp;
  } else if (props.variant === "secondary") {
    bp.color = "white";
    bp.backgroundColor = "#808080c2";
  }

  return bp;
};

const StyledButton = styled.button<IButtonProps>`
  color: ${props => (props.color ? props.color : buttonProps(props).color)};
  background-color: ${props =>
    props.backgroundColor
      ? props.backgroundColor
      : buttonProps(props).backgroundColor};
  border-radius: ${props => props.theme.borderRadius};
`;

export default StyledButton;


styled-components.d.ts

import theme from "./globals/theme";

type CustomTheme = typeof theme;

declare module "styled-components" {
  export interface DefaultTheme extends CustomTheme {}
}


那么我需要修改什么来摆脱any类型:

const buttonProps = (props: any): IButtonProps


以及以下变量的ts警告:

<StyledButton variant="primary">MyButton</StyledButton>


示例如下:
https://codesandbox.io/embed/styledcomponents-typescript-zut79?fontsize=14&hidenavigation=1&theme=dark

blmhpbnm

blmhpbnm1#

在官方文件中有描述。
.d.ts文件中添加以下内容:

import 'styled-components';

declare module 'styled-components' {
  export interface DefaultTheme {
     borderRadius: string;
     color: string;
  }
}

字符串

mw3dktmi

mw3dktmi2#

在src文件夹中,创建一个名为@types的新文件夹,并将您的文件styled.d.ts放在该文件夹中。内容同下。

import 'styled-components';
import theme from "your_theme_path";

type CustomTheme = typeof theme;

declare module "styled-components" {
  export interface DefaultTheme extends CustomTheme {}
}

字符串
它为我工作。

dced5bon

dced5bon3#

像这样将as const添加到主题对象中。

const theme = {
  borderRadius: "0.7rem",
  color: "yellow"
} as const;

字符串

q43xntqr

q43xntqr4#

由于某种原因,名称styled.d.ts不适用于类型定义。确保提供另一个名称,如style-component.d.ts

相关问题