作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在将 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>
示例在这里:
最佳答案
它在 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/
我正在尝试设置样式组件的引用。 该组件是使用 const Input = styled.input 创建的。但我无法通过 ref 获取输入值。 我的代码: const _Input = styled.
下面我创建了一个名为 Link 的样式。然而,主题在 this.props 中。从 Prop 中获取主题并传递到 Link 样式组件中的方法是什么? ReferenceError: theme is
在将 StyledComponents 与 ThemeProvider 一起使用时,我无法获得正确的类型。 我已经用这种方法试过了: https://github.com/styled-compone
我是一名优秀的程序员,十分优秀!