使用伪元素的样式组件:checked

时间:2019-06-05 12:07:57

标签: javascript reactjs css-selectors styled-components

我正在使用样式化的组件制作切换开关组件,当切换时,我想更改背景颜色。在这里,我试图选择和更改它${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;

2 个答案:

答案 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;

此处的工作沙箱:https://codesandbox.io/s/sad-thompson-sfzfv

答案 1 :(得分:-1)

尝试是否有帮助:

${SwitchInputUI} + ${SwitchSliderUI}{ 
    '&:checked':{background-color: #737A9B; }
}