我有从后端获取的数组!这是数组。
resultes
[
[front] [18:52:18] Object {
[front] [18:52:18] "cate_id": 1,
[front] [18:52:18] "name": "Vehicles",
[front] [18:52:18] },
[front] [18:52:18] Object {
[front] [18:52:18] "cate_id": 2,
[front] [18:52:18] "name": "Home",
[front] [18:52:18] },
[front] [18:52:18] Object {
[front] [18:52:18] "cate_id": 3,
[front] [18:52:18] "name": "Electronics",
},]
{this.state.categories.results.map((item ,key)=>(
<View key={key}>
<Text>{item.name}</Text>
</View> ))
如何为每个item.name添加一个基于数组键的不同图标?我试图做一个对象
const CATEGORIES_TYPES = {
car: {
style: { width: 50, fontSize: 40, height: 60, color: '#f56217' }
},
home: {
style: { width: 50, fontSize: 40, height: 60, color: '#2c3e50' }
},
tv: {
style: { width: 50, fontSize: 40, height: 60, color: 'black' }
}
};
并在渲染中:
{this.state.categories.results.map((item ,key)=>(
<View key={key}>
{CATEGORIES_TYPES[item.name] && (
<FontAwesome name={CATEGORIES_TYPES[item.name]} style={CATEGORIES_TYPES[item.name].style} />
)}
<Text>{item.name}</Text>
</View> ))
但这不起作用,这是基于密钥添加的方法吗???
使用条件渲染,或使用一个带有图标名称和类别名称作为其键的对象。
const Icons = {
Home: 'home',
Electronics: 'microchip',
Vehicles: 'car',
};
然后在渲染中
{this.state.categories.results.map((item, key) => (
<View key={key}>
{CATEGORIES_TYPES[item.name] && (
<FontAwesome
name={Icons[item.name]}
style={CATEGORIES_TYPES[item.name].style}
/>
)}
<Text>{item.name}</Text>
</View>
))}
还可以将您CATEGORIES_TYPES
的外观更改为类别对象中的键。
const CATEGORIES_TYPES = {
Vehicles: {
style: { width: 50, fontSize: 40, height: 60, color: '#f56217' },
},
Home: {
style: { width: 50, fontSize: 40, height: 60, color: '#2c3e50' },
},
Electronics: {
style: { width: 50, fontSize: 40, height: 60, color: 'black' },
},
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句