我正在用 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 响应结合起来。有什么建议吗?
最佳答案
您可以将类名存储在状态中并在您的函数中更改它。
class Demo extends Component {
constructor(props) {
super(props);
this.state = {
stClass: "lightmode"
}
}
state = {
stClass: "lightmode"
}
componentDidMount = () => {
[call your function here and change the state of stClass]
}
render() {
return (
<div className={`${this.state.stClass}`}>
[your code here]
</div>
)
}
}
关于css - 如何根据 API 收到的时间更改 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57194220/