2017-07-27 58 views
0

我有一個函數mapsarray並檢查每個記錄的狀態。每個月有一個狀態1,2或3,在if聲明中檢查。然後這些返回一些CSS來改變一個圖標的顏色。React.js:使用Map時不返回CSS的函數

_infoIconStyle() { 

    //test array 
    let monthArr = [ 
     {month:'jan', status: 1}, 
     {month:'feb', status: 2}, 
     {month:'mar', status: ''}, 
     {month:'apr', status: 1}, 
     {month:'may', status: 2}, 
     {month:'jun', status: ''}, 
     {month:'jul', status: 1}, 
     {month:'aug', status: 2}, 
     {month:'sep', status: ''}, 
     {month:'oct', status: 1}, 
     {month:'nov', status: 2}, 
     {month:'dec', status: ''} 
    ] 
    // 

    monthArr.map((monthRecord) => { 

     if(monthRecord.status == 1) { 
      const infoStyle = { 
       color: "red" 
      }; 

      return infoStyle 

     } else if(monthRecord.status == 2) { 
      const infoStyle = { 
       color: "orange" 
      }; 

      return infoStyle 

     } else { 
      const infoStyle = { 
       color: "green" 
      }; 

      return infoStyle 

     } 
    }) 
} 

我所看到的正是我所預期的console.log沒有map。但是因爲我加了map沒有CSS正在返回。

我一直沒有使用ES6很長時間,我確定它很簡單。有人可以幫忙..謝謝。

+0

'_infoIconStyle'返回undefined。 'monthArr.map(...)'沒有賦值或返回是一個noop。 –

回答

0

也許這是你的答案,我認爲你的回報還不夠遠,你沒有默認狀態,在我看來你應該嘗試類似的,但我也是新來的ES6,只是一個提示:

let newcssvar = monthArr.map((monthRecord) => { 
    let infoStyle={color:"defaulcolor-whatever"}; 
    if(monthRecord.status == 1) { 
     infoStyle = { 
      color: "red" 
     }; 

     return infoStyle 

    } else if(monthRecord.status == 2) { 
     infoStyle = { 
      color: "orange" 
     }; 

     return infoStyle 

    } else { 
     infoStyle = { 
      color: "green" 
     }; 

     return infoStyle 

    } 

    return infoStyle 

}) 
0

因爲你沒有從_infoIconStyle函數返回任何東西。另一件事是地圖將返回一個數組而不是一個單一的CSS對象。

要返回地圖的結果:

_infoIconStyle(){ 
    .... 
    return monthArr.map((monthRecord) => { //use return here 
     .... 
    } 
    .... 
} 

如果你返回地圖結果_infoIconStyle函數將返回:

[{...}, {...}, {...}, {..}, {...}, ....] 
0

所以map函數實際上返回另一個數組。在你的情況下,你正在調用map函數,但沒有將輸出分配給任何東西。如果你要將它分配給一個變量,你會有一個顏色數組。你可以嘗試的一件事是擁有一個狀態和顏色的字典,而不是使用map來獲取顏色數組。您還可以映射您的初始數組,並將顏色屬性附加到monthArr變量中的每個對象。

0
monthArr.map(monthRecord(month, i) => { 
    if(month[i].status == 1) { 
     return month[i].color = "red" 
    }; 
    return monthArr 

這種類型的函數會將相應的顏色屬性添加到循環中的每個月份。我只寫了一段代碼,因爲在下班後我沒有時間提供完整的答案。您需要額外的功能來創建樣式表。您是否嘗試使用JSX內聯呈現樣式?我需要更多信息以獲得更好的示例。如果您嘗試創建新對象而不是修改當前對象,則可以在object.Assign旁邊使用此功能。