当div内部的单选按钮签入react时,如何更改div的背景颜色



我的代码看起来像这个

<div class="radioButtonImage">
<div class="radio-wrapper">
<input class type="radio" id="Infant" value>
<img src="datarimage/png;" height="25" width="25" alt> 
<label for="Infant" class="input-label">Infant</label>
</div>
<div class="radio-wrapper">
<input class type="radio" id="Child" value>
<img src="datarimage/png;" height="25" width="25" alt> 
<label for="Child" class="input-label">child</label>
</div>
</div>

我的要求是,当单选按钮被选中时,类单选包装器的整个div背景颜色应该改为蓝色,边框应该设置为1px纯黑。如何做到这一点?

const [backgroundColor, setBackGroundColor] = React.useState("black")
const [radioButton, setRadioButton] = React.useState(false)

function setBackGroundColorFunction(){
setRadioButton((radioButton) => !radioButton)
!radioButton? setBackGroundColor("blue") : setBackGroundColor("white")
}


<div class="radio-wrapper" style={{backgroundColor: backgroundColor}}>
<input type="radio" id="Infant" checked={radioButton} onChange={()=> setBackGroundColorFunction()} />
<img src="datarimage/png;" height="25" width="25" alt>
<label for="Infant" class="input-label" style={{backgroundColor:backgroundColor}}>Infant</label>
</div>

你可以对第二台收音机做同样的处理,也可以贴标签。

或者将它们添加到其中,然后将样式携带到maindiv中以包含all。

您可以在css中使用:has()函数和:checked选择器,如下所示:

https://developer.mozilla.org/en-US/docs/Web/CSS/:has

https://developer.mozilla.org/en-US/docs/Web/CSS/:checked

.radio-wrapper:has(input:checked){
background-color: blue;
}
<div class="radioButtonImage">
<div class="radio-wrapper">
<input class type="radio" id="Infant" value>
<img src="datarimage/png;" height="25" width="25" alt>
<label for="Infant" class="input-label">Infant</label>
</div>
<div class="radio-wrapper">
<input class type="radio" id="Child" value>
<img src="datarimage/png;" height="25" width="25" alt>
<label for="Child" class="input-label">child</label>
</div>
</div>

最新更新