我使用react-native-svg模块渲染svg图标。我想要的是,当用户点击图标时,图标应该改变其颜色。因为我可以有多个图标,所以我为每个图标分配一个唯一的编号。然后对于样式道具,我检查图标的id是否在状态内,并相应地选择颜色。我正确地更新了状态,但是在重新渲染时图标没有更新。
this.state = {favoritedCalcs: []}
addToFavorite(calcId) {
let favoritedCalcs = Object.assign([], this.state.favoritedCalcs)
let updatedFavoritedCalcs
if (this.isFavorite(calcId)) {
updatedFavoritedCalcs = favoritedCalcs.filter((id) => {
return calcId !== id
})
} else {
updatedFavoritedCalcs = favoritedCalcs.concat(calcId)
}
this.setState({
favoritedCalcs: updatedFavoritedCalcs
})
}
isFavorite(calcId) {
let favoritedCalcs = this.state.favoritedCalcs
console.log(favoritedCalcs.indexOf(calcId) !== -1)
if (favoritedCalcs.indexOf(calcId) !== -1) {
return true
} else {
return false
}
}
render() {
<TouchableOpacity onPress={() => this.addToFavorite(calc.favorite_id)}>
<Svg viewBox="0 0 41 39.23" height="20" width="20">
<Path d="M21.36,2.13,25.23,14a.91.91,0,0,0,.86.63h12.5a.91.91,0,0,1,.53,1.64L29,23.63a.91.91,0,0,0-.33,1l3.86,11.89a.91.91,0,0,1-1.4,1L21,30.2a.91.91,0,0,0-1.07,0L9.85,37.55a.91.91,0,0,1-1.4-1l3.86-11.89a.91.91,0,0,0-.33-1L1.88,16.29a.91.91,0,0,1,.53-1.64h12.5a.91.91,0,0,0,.86-.63L19.64,2.13A.91.91,0,0,1,21.36,2.13Z"
fill={this.isFavorite(calc.favorite_id) ? "#FFB600" : "#1bb393"}
/>
</Svg>
</TouchableOpacity>
}
答案 0 :(得分:0)
由于我使用FlatList渲染每一行,当我尝试更新一行的样式时,React将尝试重新渲染所有行。我将shouldItemUpdate prop应用于FlatList,并改进了性能,现在使用状态更改行更新样式
<FlatList
shouldItemUpdate={(prev, next) => {return prev.item !== next.item}}
initialNumToRender={30}
/>