动态样式化组件标签名称

时间:2018-08-28 15:50:23

标签: javascript reactjs styled-components

我将styled-componentsstyled-icons一起使用。我有:

import { Facebook } from 'styled-icons/feather/Facebook'
import { Twitter } from 'styled-icons/feather/Twitter'
import { Instagram } from 'styled-icons/feather/Instagram'

...

const FacebookIcon = styled(Facebook)`
  width: 10px;
  color: black;
`

const TwitterIcon = styled(Twitter)`
  width: 10px;
  color: black;
`

const InstagramIcon = styled(Instagram)`
  width: 10px;
  color: black;
`

...

render () {
  return (
    <Fragment>
      <FacebookIcon />
      <TwitterIcon />
      <InstagramIcon />
    </Fragment>
  )
}

什么是将此代码干燥掉的好方法?

所以我可以使用以下图标: <Icon name='Facebook' /> 要么 { renderIcon(Facebook) }

1 个答案:

答案 0 :(得分:1)

您可以这样做:

import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
import { Facebook } from "styled-icons/feather/Facebook";

const IconWrapper = styled.div`
  width: 10px;
  color: black;
`;

const App = () => {
  return (
    <React.Fragment>
      <IconWrapper>
        <Facebook />
      </IconWrapper>
    </React.Fragment>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

CodeSandbox here