简体   繁体   中英

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:

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

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. can you advice me generally what is the best solution for changing styles of lots of things with if/else statement?

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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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