【问题标题】:StyledComponents with Typescript and ThemeProvider. What are the right types?带有 Typescript 和 ThemeProvider 的样式化组件。什么是正确的类型?
【发布时间】:2020-11-11 17:26:27
【问题描述】:

在将 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>
  );
}

主题.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

【问题讨论】:

    标签: reactjs typescript styled-components


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      official documentation中有描述。

      .d.ts 文件中添加:

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

      【讨论】:

        猜你喜欢
        • 2020-07-16
        • 2021-02-04
        • 2020-11-05
        • 2020-09-10
        • 2020-09-19
        • 2019-08-20
        • 2019-05-10
        • 2020-10-23
        • 2020-07-12
        相关资源
        最近更新 更多