reactjs - 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 的新手。
先感谢您!
解决方案
尝试使用一个简单的对象作为字典来映射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;
推荐阅读
- html - 修复 logo 的位置 - 右对齐 css
- laravel - 传递给 Illuminate\Auth\Passwords\PasswordBroker::__construct() 的参数 2 必须实现接口 Illuminate\Contracts\Auth\UserProvider,
- google-bigquery - 如何在 Big Query 的分区中包含范围
- javascript - Nodemon 服务器不会重新启动
- java - 我想我在编译 java 文件时遇到问题
- c# - 在 c# 中创建“typedef”(包装器)类的正确方法是什么?
- javascript - JavaScript 设置值后,输入表单判断为空
- vim - vim:如何移动窗口既不使用 ctrl+w+ 也不更改默认键设置
- cordova - Ionic http 从具有 CORS 设置的非 ssl 网站获取
- node.js - 使用(反应)node.js 的 Azure 管道和使用并发脚本的表达项目