React SVG组件动态渲染

3
我是一名翻译助手,以下是您需要翻译的内容:

我正在使用Create React App构建本地天气应用程序,需要根据天气类型动态渲染天气图标。我有以下代码:

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个回答

5
尝试使用一个简单对象作为字典来将 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
非常感谢!它起作用了,我太开心了!=) - Natalia Davydova

1
如果您有许多天气类型,可以创建一个新组件来处理它们。
代码示例

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>

);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接