[英]Changing background color depending on state in react.js
我正在開發一個簡單的應用程序,背景顏色應該因季節而異。 到目前為止,我已經寫了:
class App extends React.Component { constructor() { super(); this.state = { backgroundColor: 'blue' } } handleSeason = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()]; if (month === 'January' || month === 'February' || month === 'December') { this.setState({backgroundColor: 'white'}); } else if (month === 'March' || "April" || 'May') { this.setState({ backgroundColor: 'yellow' }); } else if (month==='June' || month ==='July' ||month ==='August'){ this.setState({ backgroundColor: 'green' }); } else { this.setState({ backgroundColor: 'red' }); } }
在渲染中,我返回以下 div:
<div className='app' style={{backgroundColor: this.state.backgroundColor }}>
背景保持藍色。 我不確定問題出在哪里。 控制台沒有顯示錯誤。 任何提示將不勝感激。
我看不到任何會觸發handleSeason
功能的東西...
也許嘗試一下會很好:
componentDidMount() {
this.handleSeason(new Date())
}
你有兩件事需要在代碼中修復
第二個 if 塊是這樣的
(month === 'March' || "April" || 'May') {
這將始終將狀態設置為黃色,因為字符串 April 和 May 將被視為真,因此如下更改
else if (month === "March" ||month === "April" ||month === "May") {
還要檢查您是否正在調用如下所示的 handleSeason 函數
this.handleSeason(new Date());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.