【问题标题】:Using Material Icons with Styled Components使用带有样式组件的材质图标
【发布时间】:2018-02-08 20:04:52
【问题描述】:

刚刚开始使用样式化组件。有没有办法设置第三方图标的样式,例如 Material Design Icons?这是我到目前为止的代码,但显然它不起作用。 相关代码在内容组件下方谢谢!

const MaterialIcon = (props) => <i className="material-icons">account_balance</i>;

const Icon = styled(MaterialIcon)`
  background-color: green;
  font-size: 50px;
`;

const CheckThisOut = props => (
  <Wrapper>
    <Header>
      <h5>{props.title}</h5>
      <Icon />
    </Header>
    <Divider />
    <Content>
      <p>5% of all participants in this campaign were first time users.</p>
    </Content>
  </Wrapper>
);

export default CheckThisOut;

【问题讨论】:

    标签: styled-components


    【解决方案1】:

    我知道这是一篇旧帖子,但这是另一种将其写为单个表达式的方式。使用样式化组件的 .attrs() (see docs) 作为类名,使用 CSS ::after 选择器作为图标名。

    const ThumbUp = styled.i.attrs(() => ({ className: "material-icons" }))`
      background-color: green;
      font-size: 50px;
      &:after {
        content: "thumb_up";
      }
    `;
    

    以更通用的方式编写它可以让您将它用于任何可用的图标。这利用了基于 props 的样式化组件能力(请参阅styled components docs 了解更多信息)。

    const MaterialIcon = styled.i.attrs(() => ({ className: "material-icons" }))`
      background-color: green;
      font-size: 50px;
      &:after {
        content: ${props => props.iconName || "help"};
      }
    `;
    

    然后你可以像这样使用它:

    <MaterialIcon iconName="check" />
    

    【讨论】:

      【解决方案2】:

      要使styled(AnyComp) 符号起作用,AnyComp 需要接受传入的 className 属性并将其附加到 DOM 节点。

      要使您的示例工作MaterialIcon 必须使用传入的className,否则样式被注入但没有DOM 节点被定位:

      const MaterialIcon = (props) => (
        <i className={`material-icons ${props.className}`}>account_balance</i>
      );
      
      // WORKS ?
      const Icon = styled(MaterialIcon)`
        background-color: green;
        font-size: 50px;
      `;
      

      请参阅我们的documentation page about styling any component 了解更多信息!

      【讨论】:

        猜你喜欢
        • 2020-05-20
        • 2020-08-02
        • 2018-10-08
        • 2015-08-02
        • 2020-06-28
        • 2020-09-13
        • 2019-12-03
        • 1970-01-01
        • 2019-02-22
        相关资源
        最近更新 更多