如何获得svg来替换react功能组件中的天气文本



反应神!我正在尝试制作一个天气应用程序,我已经能够渲染出天气的文本,但我现在想有一个天气的svg来显示。我不知道如何使它在功能组件中发挥作用。这就是我目前所得到的。我在想,如果有一种方法可以将所有svg放入变量中,那么它可以使用字符串连接,或者只使用if-then或switch语句。

import React, { useState } from 'react';
const api = {
key:"dbe4e6036b179b241f68b078f58c0c5a",
base: "https://api.openweathermap.org/data/2.5/"
}
function Data() {
const [query, setQuery] = useState('');
const [weather, setWeather] = useState({});
const search = event => {
if (event.key === "Enter") {
fetch(`${api.base}weather?q=${query}&units=imperial&APPID=${api.key}`)
.then(response => response.json())
.then(result => {
setWeather(result); 
setQuery('');
console.log(result)
})
}
}
return (
<div className="weatherApp">
<main> 
<div className="searchBox">
<input 
type="text" 
className="searchBar" 
placeholder= "How's the weather in..."
onChange={event => setQuery(event.target.value)}
value={query}
onKeyPress={search}
/>
</div>
{(typeof weather.main != "undefined") ? (
<div>
<div className="weather-box">
<div className="temp">
{Math.round(weather.main.temp)}°F
</div>
<div className="weather">
{weather.weather[0].main}
</div>
<Date />
<div className="location-box">
<div className='location'>{weather.name}</div>
</div>
</div>
</div>
) : ('')}
</main>
</div>
);
}

React允许您通过将SVG作为组件导入

import {ReactComponent as Hot} from '../path-to-hot.svg'
import {ReactComponent as Cold} from '../path-to-cold.svg'
import {ReactComponent as Rain} from '../path-to-rain.svg'
///This allows you to use the svgs as a component
export default function Weather({weather}){

// I think just creating a mapping of the text to a component is enough. 
//A switch statement would also do well here 

const weatherMap = {
hot: <Hot/>,
cold: <Cold/>,
rain: <Rain/>   
}

const currWeather = weatherMap[weather]

return <>{currWeather}</>
}

最新更新