【问题标题】::Active works in styled components but :checked doesn't:Active 在样式化组件中有效,但 :checked 无效
【发布时间】:2020-09-26 14:41:21
【问题描述】:

我正在尝试从 css 转换为样式化组件。我正在创建一个拨动开关组件。智能课程:活动类工作后,当检查交换机时,当检查复选框时,交换机不会移动到左侧,就像普通的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;

【问题讨论】:

    标签: css reactjs styled-components


    【解决方案1】:

    您的问题与样式化组件无关。规则&amp;:checked ${Button} { 假定ButtonInput 的子代,但它实际上是Input 的兄弟Label 的子代。

    将样式化组件规则更新为:

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

    Sandbox

    【讨论】:

      猜你喜欢
      • 2015-08-07
      • 2013-10-22
      • 2020-06-17
      • 1970-01-01
      • 2012-09-27
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多