我有看起来像这样的数据:
// items.json
[
{
"key": 1,
"category": "Fruits",
"colors": [
{
"color": "red",
"favourite": "apple"
},
{
"color": "orange",
"favourite": "orange"
}
]
},
{
"key": 2,
"category": "Vegetables",
"colors": [
{
"color": "orange",
"favourite": "carrot"
},
{
"color": "green",
"favourite": "celery"
}
]
}
]
但它可以在每个数组中拥有无限数量的对象。我想要做的是最初显示类别,我是这样做的:
import Items from './items.json';
// 然后我在渲染方法中使用它
render() {
var items= items;
return (
{items.map(item =>
<TouchableOpacity
key={item.key}>
<Text>
{item.category}
</Text>
</TouchableOpacity>
)}
)
}
现在,当按下类别时,我想隐藏类别并显示颜色。然后当按下颜色时,我想隐藏颜色并显示最喜欢的颜色。
我曾尝试使用 if else 语句执行此操作,但是如果替换数据,它将不起作用,并且正如我所提到的,这个 json 对象可能非常大。请帮忙!
在您的状态中声明两个数组,一个用于存储原始数据,另一个用于根据按下的项目存储过滤后的数据。
state = {
items: items, // original data
data: items, // will filter data and display using .map()
categoryIndex: 0, // index of the selected category
};
添加onPress
到您的TouchableOpacity
并传递按下的项目的类型。
{this.state.data.map((item, index) => (
<TouchableOpacity
onPress={() =>
this.onItemPress(
item.category ? 'category' : item.color ? 'color' : 'favourite',
index
)
}
key={item.key}>
<Text>{item.category || item.color || item.favourite}</Text>
</TouchableOpacity>
))}
onItemPress,基于被按下的项目更新 state.data
onItemPress = (type, index) => {
if (type === 'category') {
this.setState({
data: this.state.items[index].colors,
categoryIndex: index,
});
}
if (type === 'color') {
this.setState({
data: [
{
favourite: this.state.items[this.state.categoryIndex].colors[index]
.favourite,
},
],
});
}
if (type === 'favourite') {
this.setState({
data: this.state.items,
categoryIndex: 0,
});
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句