react-native - 将特定元素添加到地图
问题描述
我有一张从数据库中获取的地图..我想以不同的样式添加到这个数组图标中的每个项目......这是我在渲染中的地图..
{
this.state.categories.results.map((item, key) => (
<View key={key}>
<Text>{item.name}</Text>
</View>
))
}
我想为每个item.name
特定的 Fontawesome 图标添加,所以我尝试将这些带有样式的图标放在另一张地图中
const a = [
{
id: 1,
icon: "car",
style: { width: 50, fontSize: 40, height: 60, color: "#f56217" }
},
{
id: 2,
icon: "home",
style: { width: 50, fontSize: 40, height: 60, color: "#2c3e50" }
},
{
id: 3,
icon: "tv",
style: { width: 50, fontSize: 40, height: 60, color: "black" }
},
]
比我添加的渲染
<View>
{
a.map(i => (
<FontAwesome name={i.icon} style={i.style} />
))
}
<View>
{
this.state.categories.results.map((item, key) => (
<View key={key}>
<Text>{item.name}</Text>
</View>
))
}
</View>
</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: {
icon: '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={item.icon} style={CATEGORIES_TYPES[item.name].style} />
)}
<Text>{item.name}</Text>
</View>
));
推荐阅读
- java - 在 Intellij Idea 中使用 hibernate 从实体类生成数据库表(不使用 Spring)
- haskell - GHC 的 -i 标志在命令行中有效,但在 OPTIONS_GHC 中无效
- c++ - 运算符中的条件=
- javascript - 有没有办法用 Axios 发布时刻(日期和时间)?将变量“startDateStr”连接到 https
- java - 设置 spring.jpa.open-in-view=false,然后 query.unwrap(NativeQueryImpl.class) 给出异常,为什么?
- ruby-on-rails - 将“命名空间”添加到序列化程序
- javascript - 单击按钮上的自定义 Javascript 确认窗口
- sql - 在非主键或唯一键上创建外键约束
- mysql - MySQL内部将浮点值四舍五入到小数点后一位
- powerbi - Power Bi DAX:显示过去 6 个月的数据