简体   繁体   中英

React Emotion Styled Component: Class selector not working

I am creating a Radio button in React using emotion styled-components. Due to the fact we export out components into an online component repo (Bit.dev), I can not use targeted styled-components selectors and have to use classNames. I have built a switch the same way and using a class selector I can change the CSS of another component when the switch (input) is checked. However, when my toggle is changed to "checked" the class selector doesn't work:

Here is my code:

import React from "react";
import PropTypes from "prop-types";

import { Container, Input, Label, Outline, Fill } from "./styles";

const RadioButton = ({ id, ...props }) => {
  return (
    <Container>
      <Input id={id} type="radio" {...props} />
      <Label htmlFor={id}>
        <Outline className="outline">
          <Fill className="fill" />
        </Outline>
      </Label>
    </Container>
  );
};

RadioButton.propTypes = {
  id: PropTypes.string.isRequired,
};

export default RadioButton;

And styles:

import styled from "@emotion/styled";

export const Container = styled.div(() => ({}));

export const Label = styled.label(() => ({
  cursor: "pointer",
}));

export const Outline = styled.span(({ theme }) => ({
  border: `3px solid ${theme.colors.Blue}`,
  width: "24px",
  height: "24px",
  borderRadius: "100%",
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
}));

export const Fill = styled.span(({ theme }) => ({
  width: "14px",
  height: "14px",
  margin: "auto",
  borderRadius: "50%",
  background: "red",
}));

export const Input = styled.input(({ theme }) => ({
  opacity: 0,
  position: "absolute",
  "&: checked + .fill": {
    background: theme.colors.Blue,
  },
}));

As you can see when the Input is changed to "checked" the background of the fill span should change but it doesn't.

Emotion Styled Components: https://emotion.sh/docs/styled

I think the issue is come from this selector

&: checked + .fill: {
   background: theme.colors.Blue,
},

Because Input and.fill are not in same level. I've made a simple demo for it, please check https://codepen.io/doichithhe/pen/bGEQwLJ

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM