【发布时间】:2021-04-01 09:41:56
【问题描述】:
我正在制作一个 React Styled-Components 切换组件。它几乎完成了,但我只是没有得到最后一部分。这就是我所拥有的:
因此,当输入处于选中状态时,我希望在彩色 G 徽标所在的位置有一个浅灰色 G 徽标。这是我的代码:
---------VIEW:
import React from "react";
import { SwitchInput, SwitchLabel, SwitchButton } from "./toggle-style";
const Switch = ({ id, toggled, onChange }) => (
<>
<SwitchInput
id={id}
type="checkbox"
checked={toggled}
onChange={onChange}
/>
<SwitchLabel htmlFor={id}>
<SwitchButton />
</SwitchLabel>
</>
);
export default Switch;
----------STYLING:
import styled from "styled-components";
import googleIcon from "../../../assets/images/google-icon.svg";
import googleIconGrey from "../../../assets/images/google-icon-grey.svg";
import facebookIcon from "../../../assets/images/facebook-icon.svg";
import facebookIconGrey from "../../../assets/images/facebook-icon-grey.svg";
export const SwitchInput = styled.input`
height: 0;
width: 0;
visibility: hidden;
`;
export const SwitchLabel = styled.label`
display: flex;
align-items: center;
justify-content: space-between;
cursor: pointer;
width: 82px;
height: 44px;
border-radius: 50px;
position: relative;
transition: background-color 0.2s;
box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.5);
background-image: url(${facebookIconGrey});
background-position: 75% 50%;
background-repeat: no-repeat;
transition: 0.2s;
${SwitchInput}:checked & {
background-image: url(${googleIconGrey});
background-position: 25% 50%;
}
`;
export const SwitchButton = styled.span`
content: "";
position: absolute;
height: 32px;
width: 32px;
left: 6px;
top: calc(50% - 16px);
border-radius: 45px;
transition: 0.2s;
background: grey;
background: #ffffff;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.5);
background-image: url(${googleIcon});
background-repeat: no-repeat;
background-position: center;
${SwitchInput}:checked + ${SwitchLabel} & {
left: calc(100% - 6px);
transform: translateX(-100%);
background-image: url(${facebookIcon});
}
`;
感谢这位作者,因为我从他/她的沙箱中获得了大部分代码:https://codesandbox.io/s/react-styled-components-toggle-switch-3ft38
【问题讨论】:
标签: javascript css reactjs styled-components