【发布时间】: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>
【问题讨论】:
标签: reactjs typescript styled-components