Styled-components 为自定义组件添加样式

Styled-components add styles to custom component

我想借助 styled-components 库向自定义组件添加样式。我在 Whosebug 上发现了一些类似的问题和答案,但它似乎对我不起作用。我这样做:

  1. 这是我的自定义组件
const ComponentStyledBox = styled.div`
  color: red;
`;

const ComponentStyled = () => (
  <ComponentStyledBox>Component With StyledComponents</ComponentStyledBox>
);
  1. 这里我尝试使用我的自定义组件并为其添加一些样式
const ComponentStyledWrapper = styled(ComponentStyled)`
  background-color: green;
`;

export default function App() {
  return (
    <div>
      <ComponentStyledWrapper />
    </div>
  );
}

因此,我没有绿色背景。只有红色文字。如果我不使用样式化的自定义组件,而只是使用以通用方式通过 CSS 添加样式的组件,情况也是如此。我做错了什么?

为方便起见,这里有一个CodeSandbox

提前致谢!

问题是这样引起的:

const ComponentStyled = () => (
  <ComponentStyledBox>Component With StyledComponents</ComponentStyledBox>
);

您定义了一个名为 ComponentStyled 的新组件,它不是 style-able。试试这个(在 App.styles.tsx 中):

import { ComponentStyledBox } from "./components/ComponentStyled/ComponentStyled.styles";

export const ComponentStyledWrapper = styled(ComponentStyledBox)`
  background-color: green;
`;

ComponentStyledBox 是 style-able,所以你会得到绿色背景。

编辑(回复@zakharov.arthur 的评论):如果真的想要一个带有 hard-coded 个子组件的自定义组件(你确定这是你想要的吗?),你可以制作你的通过公开 ComponentStyledBox 的属性自定义组件 style-able:

// I haven't actually tried this but it should work.
const ComponentStyled = (props: Omit<Parameters<ComponentStyledBox>[0], 'children'>) =>
  <ComponentStyledBox {...props}>Component With StyledComponents</ComponentStyledBox>