【发布时间】:2018-09-17 03:08:15
【问题描述】:
我在 React App 中设置内联 CSS 样式时遇到了麻烦。因为我想根据数组中的数据更改卡片的背景颜色,但没有这样做。我正在使用具有 switch 语句的变量并将其以 as Inline 样式传递,但背景颜色没有改变。 任何人都可以帮助我解决这个问题或告诉我另一种解决方法。谢谢。
这是我的 Card.js
import React , { Component } from 'react'
export default class Card extends Component {
render(){
const {title , date , description , color } = this.props.node
let cardClass = "card-wrapper"
let myColor = ""
switch(color) {
case 'red':
myColor = 'color--red'
break;
case 'blue':
myColor = 'color--blue'
break;
case 'yellow':
myColor = 'color--yellow'
break;
case 'darkBlue':
myColor = 'color--darkBlue'
break;
default:
break;
}
return (
<div style={{ backgroundColor: myColor }}>
<div className={cardClass}>
<div className="card">
<h5 className="card-title">{title}</h5>
<p>Created on {date}</p>
<p className="card-text">{description}</p>
</div>
</div>
</div>
)
}
}
这是我的 App.css 文件
.card-wrapper {
width: 209px;
margin: .4%;
float: left;
background-color: #5cb85c;
color: white;
padding: 16px;
border-radius: 1px;
}
.color--red {
background-color: #d9534f;
}
.color--blue{
background-color: #5bc0de;
}
.color--darkBlue{
background-color: #428bca;
}
.color--yellow {
background-color: #FFD333;
}
这是我的 data.js 文件
export const data = [
{
title : 'title',
date : '1537032686201',
description : 'Some quick example text to build on the card title and make up the bulk of the cards content.',
color:'red'
},
{
title : 'title',
date : '1537032686202',
description : 'Some quick example text to build on the card title and make up the bulk of the cards content.',
color:'blue'
},
{
title : 'title',
date : '1537032686203',
description : 'Some quick example text to build on the card title and make up the bulk of the cards content.',
color:'darkBlue'
},
{
title : 'title',
date : '1537032686204',
description : 'Some quick example text to build on the card title and make up the bulk of the cards content.',
color: 'yellow'
},
]
【问题讨论】:
-
快速提示:不要切换,只需执行
let myColor = `color--${color}` -
我需要删除 switch 语句并以我的风格调用 myColor 这就是你所说的?
标签: javascript css reactjs