【问题标题】:React Emotion Styled Component: Class selector not workingReact Emotion Styled Component:类选择器不起作用
【发布时间】:2020-11-07 20:52:48
【问题描述】:

我正在使用情感样式组件在 React 中创建一个单选按钮。由于我们将组件导出到在线组件存储库 (Bit.dev) 中,我不能使用目标样式组件选择器,而必须使用类名。我以相同的方式构建了一个开关,并使用类选择器在检查开关(输入)时可以更改另一个组件的 CSS。但是,当我的切换更改为“选中”时,类选择器不起作用:

这是我的代码:

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;

和样式:

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,
  },
}));

正如您所看到的,当输入更改为“已选中”时,填充跨度的背景应该会发生变化,但不会。

情感风格的组件: https://emotion.sh/docs/styled

【问题讨论】:

    标签: javascript css reactjs emotion


    【解决方案1】:

    我认为问题来自这个选择器

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

    因为 Input 和 .fill 不在同一级别。 我已经为它做了一个简单的演示,请检查 https://codepen.io/doichithhe/pen/bGEQwLJ

    【讨论】:

    • 您好,谢谢您的回复。现在要去看看。您能否澄清一下“不在同一级别”的意思?谢谢
    • 检查了你的代码,你的意思是因为它是嵌套的,对吧?这是一个更深的层次。
    • 您的右选择器不适用于嵌套组件
    猜你喜欢
    • 2018-07-03
    • 2022-08-19
    • 2020-11-20
    • 2020-03-09
    • 2020-11-07
    • 1970-01-01
    • 2022-11-29
    • 2020-05-29
    • 1970-01-01
    相关资源
    最近更新 更多