如何为作为 props 传递的组件使用样式化组件

How to use Styled Components for a component passed as props

我在 3 个不同的文件中有 3 个组件:

//file1
const Icon1 = styled.div`
width: 10px;
`;
const Widget1 = () => <BaseWidget icon={<Icon1 />} />

//file2  
const Icon2 = styled.div`
width: 15px;
`;
const Widget2 = () => <BaseWidget icon={<Icon2 />} />

//file3
const Icon3 = styled.div`
width: 20px;
`;
const Widget3 = () => <BaseWidget icon={<Icon3 />} />

和我的基本小部件:

//basewidget
const BaseWidget = (props) => <div>{props.icon}</div>

我的问题是:如何向 basewidget 中的 props.icon 添加样式? 我可以创建一个基于 props.icon 的样式组件并添加一个通用的 css 属性 吗? 如果不可能,最好的解决方案是什么?

谢谢, 杰夫

当您传入 icon={<Icon2 />} 时,您实际上是在传递一个 JSX 元素,它不能从另一侧使用 styled-components 设置样式,因为它不是一个组件。要为组件设置样式,它需要将 className 作为 prop。在这种情况下,最好的办法是编写一个样式组件包装器 dev 并让样式级联到您的 {props.icon}

但是因为您没有将任何道具传递给 Icon,您可以轻松地将组件作为道具传递,使其具有样式。

<BaseWidget icon={Icon1} />

您在哪里收到它:

import styled from "styled-components";

const StyledIcon = styled.i``;

const BaseWidget = (props) => {
  const { Icon } = props.icon;
  return (
    <StyledIcon as={Icon} />
  );
}

as Docs