首页 > 解决方案 > 将特定元素添加到地图

问题描述

我有一张从数据库中获取的地图..我想以不同的样式添加到这个数组图标中的每个项目......这是我在渲染中的地图..

{
    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>

那么有什么方法可以在不制作另一张地图的情况下向该地图添加特定元素?最快捷的方法是什么?

标签: react-native

解决方案


您可以基于 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>
  ));

推荐阅读