【发布时间】:2022-01-25 19:17:41
【问题描述】:
我已经用谷歌搜索了无数小时以试图了解为什么这不起作用我听说状态设置系统可能是一个可能的解决方案,但我想在继续之前知道这是否有效。如果可能的话,这应该更容易解决问题。
在我的 CSS 文件中,我使用以下代码行从父级获取数据。
.cards__item__pic-wrap::after {
background-color: attr(data-Color);
}
我在父 JS 文件中这样设置这个变量
data-Color = {props.color}>
当我执行 style = {{backgroundColor: props.color}} 之类的操作时,我能够更改背景颜色,这对于许多人来说是一种常见的解决方案。 BUT 直接编辑样式而不是我在 CSS 中需要的伪样式(.cards__item__pic-wrap::after)
我当前的代码甚至没有显示任何背景颜色,我感觉 attr() 没有正确返回我的数据并导致此问题。
完整代码如下:
Cards.css
.cards__item__pic-wrap::after {
content: attr(data-category);
position: absolute;
bottom: 0;
margin-left: 10px;
padding: 6px 8px;
max-width: calc((100%) - 60px);
font-size: 16px;
font-weight: 700;
color: #fff;
background-color: attr(data-Color);
box-sizing: border-box;
}
Cards.js
import CardItem from './CardItem';
import "./Cards.css"
function Cards() {
return (
<div className='cards'>
<h1> Keep up with the latest information.</h1>
<div className = "cards__container">
<div className = "cards_wrapper">
<ul className= "cards__items" >
<CardItem
src='/images/test.jpg'
text = "Guild's are finally released! Which batch are you?"
label ="Guild News"
color = '#1f98f4'
alt = "test"
path = "/not in use"/>
</ul>
</div>
</div>
</div>
);
}
export default Cards;
CardItem.js
import {Link} from 'react-router-dom';
function CardItem(props) {
return (
<>
<li className = "cards__item" >
<Link className= "cards__item__link" to = {props.path}>
<figure className = "cards__item__pic-wrap" data-category = {props.label} data-Color = {props.color}>
<img src = {props.src} alt= {props.alt} className = "cards__item__img" />
</figure>
<div className = "cards__item__info">
<h5 className ='cards__item__text'>{props.text}</h5>
</div>
{props.color}
</Link>
</li>
</>
);
}
export default CardItem;
【问题讨论】:
标签: javascript css reactjs