2015-02-08 80 views
0

我有這個成分,風格屬性不正確更新

var ColorList = React.createClass({ 
    render: function(){ 
    var styles = { 
     colorBG: { 
     width: 100, 
     height: 100, 
     display: "inline-block", 
     border: "1px solid black" 
     } 
    }; 
    var colors = [ 
     {color: "red", hex: "#E74C3C"}, 
     {color: "white", hex: "#ECF0F1"}, 
     {color: "blue", hex: "#3498DB"}, 
     {color: "yellow", hex: "#E7D171"}, 
     {color: "green", hex: "#7AE77C"} 
    ]; 
    var colorList = colors.map(function(item){ 
     styles.colorBG.background = item.hex; 
     return (
     <span style={styles.colorBG} key={item.color}>{styles.colorBG.background}</span> 
    ) 
    }); 

    return (
     <div> 
     {colorList} 
     </div> 
    ) 
    } 
}); 

,但有趣的是,雖然在元件(styles.colorBG.background)文字工作正常,的背景顏色元素只是顏色數組中的最後一項。

任何想法?

Fiddle Here

回答

1

問題就出現了,因爲你的實際styles對象上設置每次background財產。如果您的深拷貝您的styles對象,它應該工作正常。

以下是我使用React.addons.update進行深度複製的示例。但是您也可以使用其他深層複製方法。

的jsfiddle:http://jsfiddle.net/wmg0eq18/

var colorList = colors.map(function(item){ 
     // styles.colorBG.background = item.hex; 
     var newStyle = React.addons.update(styles, { 
      colorBG: {background: {$set: item.hex}} 
     }); 
     return <span style={newStyle.colorBG} key={item.color}>{styles.colorBG.background}</span>; 
}); 
+0

有趣。這是我的第一次預感,但{styles.colorBG.background}顯示正確的文字使我無法擺脫它。是否因爲{styles.colorBG.background}被計算爲一個字符串,該字符串不會被引用傳遞,而是原始對象呢? – 2015-02-08 17:15:24

+1

' {styles.colorBG.background}'編譯爲'React.createElement(「span」,{style:styles.colorBG,key:item .color},styles.colorBG.background)'。就像你說的那樣,'styles.colorBG.background'是作爲一個字符串參數傳遞的,它引用了字符串本身。 – nilgun 2015-02-08 18:27:16

+0

有道理。謝謝@nilgun! – 2015-02-08 18:47:34