Reactjs 动态响应SVG组件渲染
我正在通过创建React应用程序在React上构建一个本地天气应用程序,我需要根据天气类型动态渲染天气图标。我有以下代码:Reactjs 动态响应SVG组件渲染,reactjs,svg,create-react-app,Reactjs,Svg,Create React App,我正在通过创建React应用程序在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 { Rea
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”导入React;
从“assets/img/weather/mist.svg”导入{ReactComponent as MistIcon};
从“assets/img/weather/rain.svg”导入{ReactComponent as RainIcon};
从“assets/img/weather/snow.svg”导入{ReactComponent as SnowIcon};
常量图标=(道具)=>{
const{weatherType}=props;
const WeatherIconName=`${weatherType}图标`;//雨、雪或雾等
返回(
//在这里,我试图渲染或
);
};
导出默认图标;
它只是抛出一个类似这样的错误:警告:该标记在此浏览器中无法识别。如果要呈现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;
const图标\u天气={
薄雾:,
雨:,
雪:
};
常量图标=道具=>{
const{weatherType}=props;
返回{ICONS[weatherType]|};
};
导出默认图标;
如果您有多种天气类型,可以创建一个新组件来处理它们() index.js
从“React”导入React;
从“react dom”导入react dom;
从“/icon”导入天气图标;
函数App(){
const weatherType='sunny';//道具硬编码,更改为'rainy'
返回(
);
}
icon.js
从“React”导入React;
从“/Rainy.svg”导入{ReactComponent as Rainy};
从“/Sunny.svg”导入{ReactComponent as Sunny};
常量图标={
雨:雨,,
晴朗的:晴朗的
};
常量IconComponent=({name,…props})=>{
让Icon=iconTypes[name];
返回;
};
导出默认IconComponent;
在你的情况下,你最终会使用
return(
<Icon size={'lg'}>
<WeatherIcon name={weatherType} />
</Icon>
);
返回(
);
非常感谢您!它起作用了,我很高兴!=)