【发布时间】:2019-12-03 06:35:30
【问题描述】:
我正在用 React 构建一个天气应用程序,到目前为止一切都很好。现在的问题是我想要一个“lightmode”和“darkmode”,它们应该是根据 API 接收到的日出/日落时间而变化的 CSS 类。当我在 vanilla JS 中执行此操作时,我使用了一个将时间戳转换为小时并将当前小时与日出/日落进行比较的函数,然后决定要呈现哪个类,就像这样
function getMode(response) {
let today = response.data.dt;
let timezone = response.data.timezone;
let difference = today + timezone - 3600;
let hours = timeConverter(difference);
let mode = document.getElementById("app");
let sunrise = response.data.sys.sunrise;
let difference2 = sunrise + timezone - 3600;
let currentSunrise = timeConverter(difference2);
let sunset = response.data.sys.sunset;
let difference3 = sunset + timezone - 3600;
let currentSunset = timeConverter(difference3) - 1;
if (hours > currentSunset) {
mode.classList.add("darkmode").remove("lightmode");
}
else if (hours < currentSunrise) {
mode.classList.add("darkmode").remove("lightmode");
} else {
mode.classList.remove("darkmode").add("lightmode");
}
}
axios.get(apiUrl).then(getMode)
<body>
<div id="app" class="lightmode">
CSS 然后看起来像这样
.lightmode h1 {
font-family: "Josefin Sans", sans-serif;
text-align: right;
color: #06384d;
font-size: 32px;
font-weight: 700;
}
.lightmode {
font-family: "Josefin Sans", sans-serif;
background-image: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);
border-style: solid;
border-radius: 30px;
border-color: #096386;
}
#app {
margin: 10px 400px;
padding: 10px 10px;
}
(...)
.darkmode h1 {
font-family: "Josefin Sans", sans-serif;
text-align: right;
color: #fff;
font-size: 32px;
font-weight: 700;
}
.darkmode {
font-family: "Josefin Sans", sans-serif;
background-image: linear-gradient(to top, #30cfd0 0%, #330867 100%);
border-style: solid;
border-radius: 30px;
border-color: #096386;
}
而且效果很好。现在在 React(这里是新手)中,我不知道如何解决这个问题。我一直在阅读有关在 React 中使用状态动态更改 CSS 类的信息,但我不知道如何将其与 API 响应合并。有什么建议吗?
【问题讨论】: