动态将反应图标加载到组件中

时间:2018-12-01 16:07:44

标签: reactjs

我正在尝试将react-icons动态加载到组件中。代码看起来像这样:

import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import * as MaterialDesign from 'react-icons/md';

const styles = {
 default: {
  flexDirection: 'column',
  alignItems: 'center'
 },
 inline: {
  flexDirection: 'row'
 }
};

const StyledTabs = styled.button`
 display: flex;
 cursor: pointer;
 color: ${props => props.color};

 ${props => styles[props.type]}
`;

const Tabs = ({ icon, type, text, color }) => {
 return (
  <StyledTabs icon={icon} type={type} text={text} color={color}>
   <span>
    <MaterialDesign.MdHome />
   </span>
   <span>{text}</span>
  </StyledTabs>
 );
};

Tabs.propTypes = {
 /** Text of tab */
 text: PropTypes.string.isRequired,
 /** Text of tab */
 type: PropTypes.oneOf(['default', 'inline']),
 color: PropTypes.string,
 icon: PropTypes.string
};

Tabs.defaultProps = {
 type: 'default',
 color: '#000',
 icon: ''
};

/**
 * @component
*/
export default Tabs;

所以我要在属性图标中添加react-icon的名称,并将字符串放在<MaterialDesign.MdHome />中,MdHome将是在属性图标中给出的字符串,例如MaterialDesign.{icon}有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

尝试一下:

const Tabs = ({ icon, type, text, color }) => {
 const mdIcon = MaterialDesign[icon];
 return (
  <StyledTabs icon={icon} type={type} text={text} color={color}>
   <span>
    <mdIcon />
   </span>
   <span>{text}</span>
  </StyledTabs>
 );
};