gpt4 book ai didi

reactjs - 带有 Typescript 和 ThemeProvider 的 StyledComponents。什么是正确的类型?

转载 作者:行者123 更新时间:2023-12-03 17:11:19 25 4
gpt4 key购买 nike

在将 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>
);
}
主题.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 {}
}

那么我必须改变什么才能摆脱 任何 输入:
const buttonProps = (props: any): IButtonProps
以及变体的 ts 警告:
<StyledButton variant="primary">MyButton</StyledButton>
示例在这里:
https://codesandbox.io/embed/styledcomponents-typescript-zut79?fontsize=14&hidenavigation=1&theme=dark

最佳答案

它在 official documentation 中有描述.
.d.ts文件添加这个:

import 'styled-components';

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

关于reactjs - 带有 Typescript 和 ThemeProvider 的 StyledComponents。什么是正确的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63029643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com