亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據react.js中的狀態更改背景顏色

根據react.js中的狀態更改背景顏色

哆啦的時光機 2023-07-06 10:16:05
我正在開發一個簡單的應用程序,背景顏色應該根據季節而不同。到目前為止我已經寫過: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 }}>背景保持藍色。我不確定問題出在哪里??刂婆_沒有顯示任何錯誤。任何提示將不勝感激。
查看完整描述

2 回答

?
滄海一幻覺

TA貢獻1824條經驗 獲得超5個贊

我沒有看到任何可以觸發該handleSeason功能的東西......

也許嘗試一下會很好:

componentDidMount() {
  this.handleSeason(new Date())
}


查看完整回答
反對 回復 2023-07-06
?
牛魔王的故事

TA貢獻1830條經驗 獲得超3個贊

您需要在代碼中修復兩件事

第二個if塊是這樣的

(month === 'March' || "April" || 'May') {

這將始終將狀態設置為黃色,因為字符串 April 和 May 將被視為 true,因此將其更改如下

   else if (month === "March" ||month ===  "April" ||month ===  "May") {

另請檢查您是否正在調用handleSeason函數,如下所示

this.handleSeason(new Date());


查看完整回答
反對 回復 2023-07-06
  • 2 回答
  • 0 關注
  • 204 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號