我正在使用样式化的组件制作切换开关组件,当切换时,我想更改背景颜色。在这里,我试图选择和更改它${SwitchInputUI}:checked + ${SwitchSliderUI}{ background-color:#737A9B;}
,但是它不起作用。我选对了吗?这是完整的代码。请帮助我
import React from 'react';
import styled from 'styled-components'
const SwitchInputUI = styled.input.attrs({ type: 'checkbox' })`
opacity: 0;
`
const SwitchUI =styled.label`
position: relative;
display: inline-block;
width: 22px;
height: 12px;
margin-bottom: 0;
vertical-align: middle;
${SwitchInputUI}:checked + ${SwitchSliderUI}{
background-color: #737A9B;
}
${SwitchInputUI}:checked + ${SwitchSliderUI}:before{
transform: translateX(10px);
}
`
const SwitchSliderUI= styled.span`
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color:#BBCDD9;
transition: .4s;
border-radius: 10px;
&:before {
content: "";
position: absolute;
width: 10px;
height: 10px;
left: 1px;
bottom: 1px;
background-color: #FFF;
transition: .4s;
border-radius: 50%;
}
`
const Switch = () => {
return (
<SwitchUI>
<SwitchInputUI/>
<SwitchSliderUI/>
</SwitchUI>
);
};
export default Switch;
答案 0 :(得分:1)
问题在于您在定义之前在SwitchSliderUI
中使用了SwitchUI
。更改顺序即可。
import React from 'react';
import styled from 'styled-components'
const SwitchInputUI = styled.input.attrs({ type: 'checkbox' })`
opacity: 0;
`
const SwitchSliderUI= styled.span`
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color:#BBCDD9;
transition: .4s;
border-radius: 10px;
&:before {
content: "";
position: absolute;
width: 10px;
height: 10px;
left: 1px;
bottom: 1px;
background-color: #FFF;
transition: .4s;
border-radius: 50%;
}
`
const SwitchUI =styled.label`
position: relative;
display: inline-block;
width: 22px;
height: 12px;
margin-bottom: 0;
vertical-align: middle;
${SwitchInputUI}:checked + ${SwitchSliderUI}{
background-color: #737A9B;
}
${SwitchInputUI}:checked + ${SwitchSliderUI}:before{
transform: translateX(10px);
}
`
const Switch = () => {
return (
<SwitchUI>
<SwitchInputUI/>
<SwitchSliderUI/>
</SwitchUI>
);
};
export default Switch;
答案 1 :(得分:-1)
尝试是否有帮助:
${SwitchInputUI} + ${SwitchSliderUI}{
'&:checked':{background-color: #737A9B; }
}