我正在尝试在触发 onPress 事件时更改 React Native Card 组件的背景颜色。虽然我在 componentDidUpdate 上看到了状态的变化,但我没有将其可视化。
我在触发 onPress 事件时更改 itemsPressed 数组的值。如果按下的项目 ID 已经在数组中,则将其删除,否则将其添加到数组中。
export default class Popular extends Component {
constructor(props) {
super(props);
this.togglePressed = this.togglePressed.bind(this);
this.state = {
categories: [],
itemsPressed: []
}
}
togglePressed = item => {
const id = item.id;
this.setState(({ itemsPressed }) => ({
itemsPressed: this.isItemPressed(item)
? itemsPressed.filter(a => a != id)
: [...itemsPressed, id],
}))
};
isItemPressed = item => {
const id = item.id;
return this.state.itemsPressed.includes(id);
};
componentDidMount() {
this.setState({
categories:this.props.categories,
});
}
componentDidUpdate(){
console.log(this.state.itemsPressed);
}
renderTabItem = ({ item,index }) => (
<TouchableOpacity
style={styles.category}
key={index}
onPress={() => this.togglePressed(item)}
>
<Card center
style={[styles.card,{backgroundColor:
this.isItemPressed(item)
? item.color
: 'gray'
}]}>
<Image source={item.icon} style={styles.categoryIcon}/>
</Card>
<Text size={12} center style={styles.categoryName}
medium color='black'
>
{item.name.toLowerCase()}
</Text>
</TouchableOpacity>
);
renderTab(){
const {categories} = this.state;
return (
<FlatList
horizontal = {true}
pagingEnabled = {true}
scrollEnabled = {true}
showsHorizontalScrollIndicator={false}
scrollEventThrottle={16}
snapToAlignment='center'
data={categories}
keyExtractor={(item) => `${item.id}`}
renderItem={this.renderTabItem}
/>
)
}
render() {
return (
<ScrollView>
{this.renderTab()}
</ScrollView>
);
}
}
我期待视觉上的变化,但我无法重新渲染 renderTab()。
谢谢!
最佳答案
您的 FlatList
具有属性 category
作为数据源,因此它仅在检测到 category
发生变化时才重新呈现单元格属性(property)。但是,您的代码仅更改 itemsPressed
,因此不会重新呈现任何单元格。
您可以通过在 extraData 属性中指定 FlatList
来监听 state.itemsPressed
的变化:
extraData={this.state.itemsPressed}
关于javascript - View 在 onPress 后不重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56396507/