【发布时间】:2019-10-17 04:29:54
【问题描述】:
我正在尝试在触发 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()。
谢谢!
【问题讨论】:
-
看看extraData 属性。添加
extraData={categories}能解决您的问题吗? -
哇,非常感谢!我为 extraData 属性分配了一个布尔值,然后在触发 onPress 时更改了它的状态。