首页 > 解决方案 > React SVG 组件动态渲染

问题描述

我正在通过 Create React App 在 React 上构建本地天气应用程序,我需要根据天气类型动态呈现天气图标。我有这个代码:

import React from 'react';

import { ReactComponent as MistIcon } from 'assets/img/weather/mist.svg';
import { ReactComponent as RainIcon } from 'assets/img/weather/rain.svg';
import { ReactComponent as SnowIcon } from 'assets/img/weather/snow.svg';

const icon = (props) => {

    const { weatherType } = props;

    const WeatherIconName = `${weatherType}Icon`; //Rain or Snow or Mist etc


    return(

        <Icon size={'lg'}>
            <WeatherIconName/> //here I'm trying to render <MistIcon/> or <SnowIcon/> or <RainIcon/>
        </Icon>

    );

};

export default icon;

它只是抛出这样的错误:警告:此浏览器中无法识别该标签。如果您打算渲染一个 React 组件,请以大写字母开头。

但是,如果我明确地命名它,像这样,它可以工作并呈现一个正确的图标:

return(

  <Icon size={'lg'}>
     <MistIcon/>
  </Icon>

);

如果可能的话,请帮助我增强我的代码以动态呈现图标。对不起,如果问题很简单,我是 React 的新手。

先感谢您!

标签: reactjssvgcreate-react-app

解决方案


尝试使用一个简单的对象作为字典来映射weatherType到特定的图标:

const ICONS_WEATHER = {
  Mist: <MistIcon />,
  Rain: <RainIcon />,
  Snow: <SnowIcon />
};

const icon = props => {
  const { weatherType } = props;

  return <Icon size={'lg'}>{ICONS[weatherType] || <DefaultIcon />}</Icon>;
};

export default icon;

推荐阅读