mar*_*dro 6 typescript reactjs styled-components
在将 StyledComponents 与 ThemeProvider 一起使用时,我无法获得正确的类型。
我用这种方法尝试过:https : //github.com/styled-components/styled-components/issues/1589
到目前为止我的代码:
应用程序.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>
);
}
Run Code Online (Sandbox Code Playgroud)
主题.ts
import "styled-components";
const theme = {
borderRadius: "0.7rem",
color: "yellow"
};
export default theme;
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
styled-components.d.ts
import theme from "./globals/theme";
type CustomTheme = typeof theme;
declare module "styled-components" {
export interface DefaultTheme extends CustomTheme {}
}
Run Code Online (Sandbox Code Playgroud)
那么我必须改变什么才能摆脱以下任何类型:
const buttonProps = (props: any): IButtonProps
Run Code Online (Sandbox Code Playgroud)
以及变体的 ts 警告:
<StyledButton variant="primary">MyButton</StyledButton>
Run Code Online (Sandbox Code Playgroud)
示例在这里:https :
//codesandbox.io/embed/styledcomponents-typescript-zut79?fontsize=14&hidenavigation=1&theme=dark
小智 20
官方文档中有描述。
在文件中.d.ts添加以下内容:
import 'styled-components';
declare module 'styled-components' {
export interface DefaultTheme {
borderRadius: string;
color: string;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 15
在 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 {}
}
Run Code Online (Sandbox Code Playgroud)
它对我有用。
小智 2
as const像这样添加到您的主题对象。
const theme = {
borderRadius: "0.7rem",
color: "yellow"
} as const;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3147 次 |
| 最近记录: |