提问者:小点点

:active在样式化组件中工作,但:checked不工作


我正在尝试从css过渡到样式组件。我正在创建一个切换开关组件。选中开关时:active类上的动画会工作,但选中复选框时,开关不会像普通CSS那样向左移动。

import React from 'react';
import styled from 'styled-components'

const Button = styled.span`
  content: '';
  position: absolute;
  top: 3.7px;
  left: 5px;
  width: 42px;
  height: 42px;
  border-radius: 45px;
  transition: 0.2s;
  background: #fff;
  box-shadow: 0 0 2px 0 rgba(10, 10, 10, 0.29);
`;

const Label = styled.label`
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  width: 100px;
  height: 50px;
  background: dodgerblue;
  border-radius: 100px;
  position: relative;
  transition: background-color 0.2s;
  &:active ${Button} {
    width: 50px;
  }
`;

const Input = styled.input`
  height: 0;
  width: 0;
  visibility: hidden;
  &:checked ${Button} {
    left: calc(100% - 5px);
    transform: translateX(-100%);
  }
`;

const Switch = ({ isOn, handleToggle, onColor }) => {
  return (
    <>
      <Input
        checked={isOn}
        onChange={handleToggle}
        className='react-switch-checkbox'
        id={`react-switch-new`}
        type='checkbox'
      />
      <Label
        style={{ background: isOn && onColor }}
        className='react-switch-label'
        htmlFor={`react-switch-new`}>
        <Button className={`react-switch-button`} />
      </Label>
    </>
  );
};

export default Switch;

共1个答案

匿名用户

您的问题与样式组件无关。规则&:checked${Button}{假定按钮输入的子级,但它实际上是输入的同级标签的子级。

将样式组件规则更新为:

&:checked + ${Label} ${Button} {
  left: calc(100% - 5px);
  transform: translateX(-100%);
}

沙箱