React SVG组件动态渲染

时间:2019-11-02 18:00:01

标签: reactjs svg create-react-app

我正在通过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的新手。

提前谢谢!

2 个答案:

答案 0 :(得分:1)

尝试使用简单的对象作为字典,将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;

答案 1 :(得分:1)

如果天气类型很多,则可以创建一个新组件来处理它们。
Code example

index.js

import React from "react";
import ReactDOM from "react-dom";
import WeatherIcon from "./icon";

function App() {

  const weatherType = 'sunny'; // props hardcoded, change to 'rainy'

  return (
    <div>
      <WeatherIcon name={weatherType} />
    </div>
  );
}


icon.js

import React from "react";
import { ReactComponent as Rainy } from "./rainy.svg";
import { ReactComponent as Sunny } from "./sunny.svg";

const iconTypes = {
  rainy: Rainy,
  sunny: Sunny
};

const IconComponent = ({ name, ...props }) => {
  let Icon = iconTypes[name];
  return <Icon {...props} />;
};

export default IconComponent;

以您为例,您最终将使用

return(

  <Icon size={'lg'}>
     <WeatherIcon name={weatherType} />
  </Icon>

);