我已經用谷歌搜索了無數小時以試圖了解為什么這不起作用我聽說狀態設定系統可能是一個可能的解決方案,但我想在繼續之前知道這是否有效。如果可能的話,這應該更容易解決問題。
在我的 CSS 檔案中,我使用以下代碼行從父級獲取資料。
.cards__item__pic-wrap::after {
background-color: attr(data-Color);
}
我在父 JS 檔案中設定了這個變數
data-Color = {props.color}>
當我執行 style = {{backgroundColor: props.color}} 之類的操作時,我能夠更改 backgroundColor,這對許多人來說是一種常見的解決方案。但是直接編輯樣式而不是我在 CSS 中需要的偽樣式(.cards__item__pic-wrap::after)
我當前的代碼甚至沒有顯示任何背景顏色,我感覺 attr() 沒有正確回傳我的資料并導致這種情況。
完整代碼如下:
卡片.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;
uj5u.com熱心網友回復:
您可以使用此代碼實作您的目標!
//在你的css檔案中
.cards__item__pic-wrap {
background-color: var(--data-color);
}
// 在你的CardItem.js檔案中
<figure style={{ '--data-color': props.color, }} className="cards__item__pic-wrap" data-category={props.label}>
<img src={props.src} alt={props.alt} className="cards__item__img" />
</figure>
uj5u.com熱心網友回復:
你可以在你的css中做這樣的事情:
.cards__item__pic-wrap[data-Color] {
background-color: attr(data-Color)
}
您只會修改定義了該屬性的圖片包裝器。在您的組件中檢查是否設定了 data-Color 否則在沒有 data-Color 的情況下渲染它
所以如果 prop.color 是未定義的渲染像這樣:
<figure className = "cards__item__pic-wrap" data-category = {props.label}>
<img src = {props.src} alt= {props.alt} className = "cards__item__img" />
</figure>
否則
<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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/421157.html
標籤:
上一篇:懸停時導航欄背景顏色
下一篇:兩個元素不在移動視圖中居中
