我有以下名為 Card 的組件:
<article className={styles.card_container}>
<input type="checkbox" className={styles.checkbox} onClick={setCheckbox}/>
<div className={styles.text_container} id="txt_container">
<span>
{props.number}
</span>
</div>
</article>
哪個應該顯示復選框,沒有勾選 - 容器是否檢查,具有背景顏色,取決于此復選框是否被選中。例如,未選中時應為紅色,但選中時為黑色。為此,我決定使用狀態:
const [isChecked, setChecked] = useState(false);
const setCheckbox = (e) => {
if (isChecked===true){
setChecked(false);
document.getElementById("txt_container").style.backgroundColor="#a81616";
}else {
setChecked(true);
document.getElementById("txt_container").style.backgroundColor="#000";
}
}
我想創建一些此類組件,因此我決定將其與陣列中的資訊進行映射:
{data.map(element=>
<Card number={element.option} key={element.option}/>)
}
(其中 data 是一個帶有數字物件的陣列, Card 是使用上面的代碼創建的組件)。問題是,當我“檢查”其他組件時,它一開始只會改變顏色。為什么會這樣?我很感激任何幫助。
還有一些css代碼:
.card_container {
position: relative;
width: 60px;
height: 45px;
margin: 5px;
float: left;
border: 2px solid #50bcf2;
box-sizing: border-box;
}
.text_container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
line-height: 25px;
transition: .5s ease;
}
.checkbox {
position: absolute;
top: 0;
left: 0;
width: 60px;
height: 45px;
opacity: 1;
cursor: pointer;
}
我想通過js來做這個,有沒有其他方法可以做到這一點(不是css)?或者,也許我可以將 props 提供的背景顏色從例如陣列注入到 Card 組件?
uj5u.com熱心網友回復:
您可以style在反應組件上使用屬性
<div className={styles.text_container} style={{backgroundColor: isChecked? #a81616 : #000}}>
您的代碼不起作用,因為 ID 應該是唯一的,并且您只選擇第一次出現...如果您想在反應中使用 DOM,請不要使用getElementByID和使用useRef()反應。它的更“反應”方式如何做到這一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/405654.html
標籤:
上一篇:Vue沒有在組件中傳遞資料
