在react中逐个使用不同类css的好方法?

2024-01-16

如果温度处于不同区域,我想使用不同的颜色。

这是我的代码:

    const [weatherColor, setWeatherColor] = useState({
            temperature: '',
            humidity: ''
        })
    const colour = (temp, hum) => {
            let temperature = '';
            let humidity = '';
            if(temp < 11) temperature = 'bluegreen';
             else if(temp >= 11 && temp < 24) temperature = 'green';
             else if(temp >= 24 && temp < 36) temperature = 'orange';
             else if(temp > 36) temperature = 'purple';
             else temperature = 'gray';
            if(hum < 30) humidity = '30';
             else if(hum >= 30 && hum < 60) humidity = '60';
             else if(hum >= 60 && hum < 100) humidity = '100';
             else humidity = 'gray';
            setWeatherColor({temperature, humidity});
        }

这是我添加 CSS 的位置:

    <span className={`pt-8 text-temp-${weatherColor.temperature} text-[90px]`}>{observationalData.temperature}&#176;C</span>

使用 console.log,我可以看到 ${weatherColor.Temperature} 的值,这正是我所期望的: “文本-温度-紫色”。但是我页面上的颜色没有改变。可能出什么问题了?

这是整个代码:

    import axios from 'axios';
    import { useEffect, useState } from 'react';
    import Icon from './Icon';
    
    const table = {
        day: {
            '晴天': { MappedIcon: Icon.SunDay },
            '多雲': { MappedIcon: Icon.CloudDay },
            '陰天': { MappedIcon: Icon.CloudyDay },
            '有雨': { MappedIcon: Icon.RainDay },
            '雷雨': { MappedIcon: Icon.RainLightningDay },
            '下雪': { MappedIcon: Icon.SnowDay },
        },
        night: {
            '晴天': { MappedIcon: Icon.SunNight },
            '多雲': { MappedIcon: Icon.CloudNight },
            '陰天': { MappedIcon: Icon.CloudyNight },
            '有雨': { MappedIcon: Icon.RainNight },
            '雷雨': { MappedIcon: Icon.RainLightningNight },
            '下雪': { MappedIcon: Icon.SnowNight },
        }
    }
    
    export default function Weather() {
        const [observationalData, setObservationalData] = useState({
            ctyName: '',
            townName: '',
            stationId: '',
            stationName: '',
            timestamp: 0,
            time: '',
            observationDate: '',
            observationTime: '',
            temperature: 0,
            day: '',
            title: '',
            humidity: 0
        });
    
        const [weatherColor, setWeatherColor] = useState({
            temperature: '',
            humidity: ''
        })
    
        const [WeatherIcon, setWeatherIcon] = useState();
    
        const colour = (temp, hum) => {
            let temperature = '';
            let humidity = '';
            if(temp < 11) temperature = 'bluegreen';
             else if(temp >= 11 && temp < 24) temperature = 'green';
             else if(temp >= 24 && temp < 36) temperature = 'orange';
             else if(temp > 36) temperature = 'purple';
             else temperature = 'gray';
            if(hum < 30) humidity = '30';
             else if(hum >= 30 && hum < 60) humidity = '60';
             else if(hum >= 60 && hum < 100) humidity = '100';
             else humidity = 'gray';
            setWeatherColor({temperature, humidity});
        }
    
        const getPosition = () => {
            if(!navigator.geolocation) {
                console.log('geolocation is not support');
            } else {
                const success = async (position) => {
                    const crd = position.coords;
                    const { latitude, longitude } = crd;
                    const data = await axios.get(`http://localhost:8000/api?latitude=${latitude}&longitude=${longitude}`);
                    setObservationalData(data.data);
                    const { MappedIcon } = table[observationalData.day][observationalData.title];
                    console.log(MappedIcon);
                    setWeatherIcon(MappedIcon);
                    colour(observationalData.temperature, observationalData.humidity);
                }
                const error = err => {
                    console.log('err', err.message);
                }
                navigator.geolocation.getCurrentPosition(success, error);
            }
        };
    
        useEffect(() => {
            const timer = setInterval(getPosition, 5000);
            console.log(new Date());
    
            return () => {
                clearInterval(timer);
            };
        });
        
        useEffect(() => {
            getPosition();
        }, []);
    
        return (
            <div className="flex">
                <div>{WeatherIcon ? <WeatherIcon /> : ''}</div>
                <div className="flex flex-wrap justify-center w-[664px]">
                    <span className={`pr-2 w-[50px] text-temp-${weatherColor.temperature} text-[40px]`}>溫度</span>
                    <span className={`pt-8 text-temp-${weatherColor.temperature} text-[90px]`}>{observationalData.temperature}&#176;C</span>
                    {console.log(`text-temp-${weatherColor.temperature}`)}
                    <span className="px-8">|</span>
                    <span className={`pr-2 text-rh-${weatherColor.humidity} w-[50px] text-[40px]`}>濕度</span>
                    <span className={`pt-8 text-rh-${weatherColor.humidity} text-[90px]`}>{observationalData.humidity}%</span>
                    <span className="text-[50px]">{observationalData.ctyName},{observationalData.townName}</span>
                </div>
            </div>
        )
    };

Tailwind 生成的 CSS 文件将仅包含它在扫描代码时识别的类,这意味着动态生成的类(例如text-temp-${weatherColor.temperature})将不会被包括在内,除非每个颜色实用程序类(例如text-temp-purple) 作为完整字符串出现在代码中的其他位置。

您可以通过将完整的实用程序类设置为颜色来解决此问题:

if(temp < 11) temperature = 'text-temp-bluegreen';

...

<span className={`pt-8 ${weatherColor.temperature} text-[90px]`}>

或者保存颜色值并使用style属性:

if(temp < 11) temperature = '00DDDD';

...

<span style={{color: `#${weatherColor.temperature}`}} className={`pt-8x text-[90px]`}>

或者查找对象中的颜色字符串并使用style属性:

if(temp < 11) temperature = 'bluegreen';

...

const colors = {
  'bluegreen': '#00DDDD',
  'green': '#008000',
}

<span style={{color: colors?[weatherColor.temperature] ?? ''`}} className={`pt-8x text-[90px]`}>

更多信息:https://tailwindcss.com/docs/content-configuration#dynamic-class-names https://tailwindcss.com/docs/content-configuration#dynamic-class-names

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在react中逐个使用不同类css的好方法? 的相关文章

随机推荐