简体   繁体   English

无法在 if/else 代码块中正确设置元素样式

[英]Can't style element correctly in if/else codeblock

I have some data from dummy back-end for example:我有一些来自虚拟后端的数据,例如:

[
 {
  "title": "title title 0",
  "date": "22/09/2015",
  "author": "author00",
  "langs": [
   "react",
   "javascript"
   ]
 },
 {
 "title": "title 1",
 "date": "09/11/2012",
 "author": "author188",
 "langs": [
 "angular",
 "vue"
   ]
 }],

I try to stylize "langs" array by it's first element, example:我尝试通过它的第一个元素来风格化“langs”数组,例如:

const posts = this.state.posts.map(post => {
      if (post.tags[0].startsWith("react")){
        post.style.backgroundColor = "red";
        }
      }

I think 'if' statement is correct but I don't know what to try in codeblock.我认为“if”语句是正确的,但我不知道在代码块中尝试什么。 when I try to log in console somewhat it is ok.当我尝试登录控制台时,它可以。 but many things on this case depends on what is the first [0] element in the array...但是这种情况下的很多事情取决于数组中的第一个 [0] 元素是什么......

for example, if first element contains 'angular' in cideblock many style options must be rearanged on red color, and when it contains 'react' the dominant style color in every case must be a blue color.例如,如果第一个元素在 cideblock 中包含 'angular',则许多样式选项必须重新排列为红色,并且当它包含 'react' 时,每种情况下的主导样式颜色都必须是蓝色。 can you advice me generally what is the best solution for changing styles of lots of things with if/else statement?你能告诉我用 if/else 语句改变很多东西的风格的最佳解决方案是什么?

Make a color map that defines colors for code tags like this:制作一个颜色图,定义代码标签的颜色,如下所示:

const colorMap = { 'react': 'red', 'angular': 'blue' };

then use it like this:然后像这样使用它:

const posts = this.state.posts.map(post => {
      const tag = post.tags[0];
      const color = colorMap[tag];
      post.style.backgroundColor = color;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM