#reactjs
#reactjs
Вопрос:
Я делаю некоторые вещи pokedex (например, pokemon wikipedia). Идея в том, что у каждого покемона есть хотя бы один тип (или категория). Я хочу настроить эти блоки (с именами типов) в отношении объекта typesAndColors, чтобы блок grass был зеленым, блок fire — красным и т.д.
const typesAndColors = {
"normal":
{
backgroundColor: "#A3CB38",
color: "#000"
},
"fighting":
{
backgroundColor: "#3B3B98",
color: "#000"
},
"flying":
{
backgroundColor: "#9AECDB",
color: "#000"
},
"poison":
{
backgroundColor: "#a29bfe",
color: "#000"
},
"ground":
{
backgroundColor: "#4b4b4b",
color: "#000"
},
"rock":
{
backgroundColor: "#ccae62",
color: "#000"
},
"bug":
{
backgroundColor: "#badc58",
color: "#000"
},
"ghost":
{
backgroundColor: "#dfe6e9",
color: "#000"
},
"steel":
{
backgroundColor: "#95afc0",
color: "#000"
},
"fire":
{
backgroundColor: "#ff3838",
color: "#000"
},
"water":
{
backgroundColor: "#3498db",
color: "#000"
},
"grass":
{
backgroundColor: "#2ecc71",
color: "#000"
},
"electric":
{
backgroundColor: "#fdcb6e",
color: "#000"
},
"psychic":
{
backgroundColor: "#BDC581",
color: "#000"
},
"ice":
{
backgroundColor: "#c7ecee",
color: "#000"
},
"dragon":
{
backgroundColor: "#30336b",
color: "#fff"
},
"dark":
{
backgroundColor: "#2C3A47",
color: "#fff"
},
"fairy":
{
backgroundColor: "#e056fd",
color: "#000"
},
"unknown":
{
backgroundColor: "#000",
color: "#000"
},
"shadow":
{
backgroundColor: "#636e72",
color: "#000"
}
};
...
let items = [],
itemSet = [];
const styles = {
backgroundColor: "",
color: ""
};
// arr consists of types (this info is fetched from url)
// example:
// [ [ grass, poison ], [ fire ], [ water ] ]
arr.forEach(element => {
element.forEach(el => {
styles.backgroundColor = typesAndColors[el].backgroundColor;
styles.color = typesAndColors[el].color;
itemSet.push(
<div className="container__block" style={ styles }>
{el}
</div>
);
})
items.push(itemSet);
itemSet = [];
})
...
// in the end, I paste { items } on a web-page
Проблема в том, что все блоки одного цвета (посмотрите на скриншот ниже).
Ответ №1:
Вам нужно создать новый styles
объект для каждого. В противном случае все они становятся общими, когда приходит время для рендеринга.