使用React,如何使用名称中的变量调用模块?

时间:2018-04-13 02:25:17

标签: javascript reactjs

我正在使用此React组件动态加载SVG图标。为什么没有<MyIcon.icons[{name}] />工作?

import React from 'react';
import PropTypes from 'prop-types';

import {
  IconHome,
  IconCow,
  IconDog,
} from '../Icon';


const MyIcon = ({
  name,
}) => (
  <div>
    <MyIcon.icons[{name}] />
    {name}
  </div>
);

MyIcon.icons = {
  home: IconHome,
  dog: IconCow,
  cow: IconDog,
};

MyIcon.propTypes = {
  name: PropTypes.string.isRequired,
};

export default MyIcon;

我得到以下错误信息:

Module build failed: SyntaxError: Unexpected token (13:22)

1 个答案:

答案 0 :(得分:1)

实现此目的的最简单方法是将要包含的组件分配给变量,如下所示:

import React from 'react';
import PropTypes from 'prop-types';

import {
  IconHome,
  IconCow,
  IconDog,
} from '../Icon';

const icons = {
  home: IconHome,
  dog: IconCow,
  cow: IconDog,
};

const MyIcon = ({ name }) => {
  const SelectedIcon = icons[name];
  return (
    <div>
      <SelectedIcon />
      {name}
    </div>
  )
};

MyIcon.propTypes = {
  name: PropTypes.string.isRequired,
};

export default MyIcon;