0
在我的項目中,我試圖改變我的ListView的背景顏色。 顏色已經在一個數組內部,並且組件內部會堆積起來,我首先獲取rand數字,這樣每次用戶打開組件時,它都會以不同的顏色開始。ListView動態樣式反應原生
如何在每次調用renderRow時更改顏色的狀態。我嘗試添加的setState但它造成最大調用堆棧錯誤..
constructor(props){
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
color: null,
}
}
componentWillMount() {
var rand = Math.floor((Math.random()*8)+1);
this.setState({ color: rand});
}
_renderRow (rowData, rowId, rowColumn) {
var temp=(this.state.color+1)%8;
this.setState({color: temp});
return (
<View style={{ backgroundColor: backColor[temp] ,paddingVertical: 10, paddingHorizontal: 10, marginBottom: 10, borderRadius: 5 }}>
<Text>{rowData.name}</Text>
</View>
)
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderRow.bind(this)}
style={styles.mainContainer}
/>
);
}
}
任何人都可以點我到正確的方向?
問題是所有的行都使用'color'的相同引用,所以當一行更改它時,子行需要重新渲染,並且這樣做也修改'color'。將_renderRow組件移出到一個合適的子組件,該組件根據來自父項的靜態輸入管理其自己的顏色將解決問題。 –
哦..我明白了..好吧..我會按照你的建議嘗試。謝謝! –