使用主题时如何将道具传递给样式组件?

时间:2021-04-03 05:19:13

标签: reactjs typescript styled-components

我想使用从 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 获取主时,我希望它从我制作的主题上下文中获取颜色代码。

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的问题,您有几种主题颜色,并且您想从传递给组件的 prop 中指定要使用的颜色。

给定主题颜色:

colors: {
  primary: "#5A8DEE",
  boldPrimary: "#274d8c",
  lightPrimary: "#dae3f5",
  green: "#5CCf4C",
  gray: "#F2F4F4",
  white: "#FFFFFF",
  text: "#5f5f63",
  lightText: "#878791",
}

您可以指定一个 color 道具:

interface Props extends React.ComponentPropsWithoutRef<"button"> {
  color?: string;
  padding?: string;
}

在样式组件中,使用传递的 color 道具访问您的主题

const StyledButton = styled("button")<{
  color: string;
  padding: string;
}>`
  background: ${(props) => props.theme.colors[props.color]}; // <-- access by dynamic key
  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;
`;

const Button = ({ children, color, padding }: Props) => {
  return (
    <StyledButton color={color} padding={padding!}>
      {children}
    </StyledButton>
  );
};

然后指定您要使用的颜色:

<Button color="primary" />
<Button color="boldPrimary" />
...etc...