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

卡斯特利

我有一些来自虚拟后端的数据,例如:

[
 {
  "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"
   ]
 }],

我尝试通过第一个元素来样式化“ langs”数组,例如:

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

我认为'if'语句是正确的,但我不知道在代码块中尝试什么。当我尝试登录控制台时就可以了。但是这种情况下的很多事情取决于数组中的第一个[0]元素是什么...

例如,如果cideblock中的第一个元素包含“ angular”,则许多样式选项必须重新设置为红色,而当其包含“ react”时,则每种情况下的主导样式颜色都必须为蓝色。您能否一般地建议我,使用if / else语句更改许多样式的最佳解决方案是什么?

une

制作一个颜色图,为代码标签定义颜色,如下所示:

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

然后像这样使用它:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章