【发布时间】:2021-06-29 20:03:09
【问题描述】:
我想使用从 Button 组件中获得的颜色道具,以使用样式化组件主题将其用作背景颜色。
import React from "react";
import styled from "styled-components";
const StyledButton = styled("button")<{
color: string;
padding: string;
}>`
background: ${(props) => props.theme.colors.primary};
outline: none;
box-shadow: none;
border: none;
padding: ${(props) => props.padding};
border-radius: 5px;
color: white;
font-size: ${(props) => props.theme.fontSizes.small};
margin: 0 10px;
`;
interface Props extends React.ComponentPropsWithoutRef<"button"> {
color?: string;
padding?: string;
}
const Button = ({ children, color, padding }: Props) => {
return (
<StyledButton color={color!} padding={padding!}>
{children}
</StyledButton>
);
};
export default Button;
主题:
import { DefaultTheme } from "styled-components";
const theme: DefaultTheme = {
colors: {
primary: "#5A8DEE",
boldPrimary: "#274d8c",
lightPrimary: "#dae3f5",
green: "#5CCf4C",
gray: "#F2F4F4",
white: "#FFFFFF",
text: "#5f5f63",
lightText: "#878791",
},
fontSizes: {
extraSmall: "0.75rem",
small: "1rem",
medium: "1.25rem",
large: "1.50rem",
},
};
export default theme;
就像我从 Button props 中获取主要内容一样,我希望它从我制作的主题上下文中获取颜色代码。
【问题讨论】:
-
您使用的是theme provider吗?
-
是的,我愿意。
background: ${(props) => props.theme.colors.primary};和font-size: ${(props) => props.theme.fontSizes.small};工作得很好。 -
那么如果访问
theme有效,那么问题/问题是什么?对不起,我只是不明白你在问什么。 -
因此,如果您查看按钮组件,它会获得我想在样式组件中使用它们的道具。因此,如果我得到的道具是原色或任何其他颜色,我想在
${(props) => props.theme.colors.primary};中使用它。我可以做有条件的,但为所有 +10 种颜色做这件事很麻烦。 -
什么是
primary?props.theme.colors.primary?它在您所说的工作的theme道具中传递。您是说您的主题有多个theme.color属性,并且您想从传递的道具中指定哪个?
标签: reactjs typescript styled-components