我正在建立一个天气应用程序的反应,到目前为止还不错。现在的问题是,我想要一个"lightmode“和"darkmode”,这应该是根据API接收到的日出/日落时间变化的CSS类。在使用香草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;
}而且效果很好。现在,在反应(这里的新手)我不知道如何处理这个问题。我一直在阅读关于动态更改CSS类以响应状态的文章,但是我不知道如何将它与API响应结合起来。有什么建议吗?
发布于 2019-07-25 04:34:09
您可以在状态中存储className并在函数中更改它。
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>
)
}
}发布于 2019-07-25 04:29:41
在React中动态更改CSS类的关键部分是:
<div className={`App ${this.state.displayMode}`}>容器的类名将在更改displayMode的状态时更新,并在本例中追加到类App,从而生成App darkmode并呈现为此类。
<div class="App darkmode">示例代码/用例:
class App extends Component {
state = {
displayMode: "lightmode"
};
getMode = response => {
let _displayMode;
// Logic for determining the mode
return _displayMode;
}
componentDidMount() {
// Make API call here and run your logic to determine the mode
axios.get(apiUrl).then(getMode).then(displayMode => {
// As a callback to your function, set the state for displayMode
this.setState({
displayMode: displayMode
})
});
}
render() {
return (
<div className={`App ${this.state.displayMode}`}>
</div>
);
}
}https://stackoverflow.com/questions/57194220
复制相似问题