【问题标题】:How to style a label when input inside it is checked?检查标签内部输入时如何设置标签样式?
【发布时间】:2021-10-13 08:35:16
【问题描述】:

here我有一个代码,我在检查输入时更改标签的背景,但标签就在输入之后,如下例所示。

const Label = styled.label`
  background: red;
  display: block;
  padding: 1rem;
`;

const Input = styled.input`
  &:checked + ${Label} {
    background: blue;
  }
`;

const App = () => (
  <div>
    <Input id="input" type="checkbox" />
    <Label for="input" />
  </div>
);

但是如果输入在标签内,怎么可能改变标签背景呢?如下例所示:

const App = () => (
  <div>
    <Label for="input" />
       <Input id="input" type="checkbox" />
    </Label>
  </div>
);

【问题讨论】:

    标签: reactjs checkbox styled-components


    【解决方案1】:

    你不能像styled-components一样在css中使用bubbling stage。但是您可以从input 获取事件,然后传入styled-componentexample

    import { useState } from "react";
    import styled from "styled-components";
    
    const Label = styled.label`
      background: ${({ checked }) => (checked ? "blue" : "red")};
      display: block;
      padding: 1rem;
    `;
    
    const Input = styled.input`
      /* &:checked + ${Label} {
        background: blue;
      } */
    `;
    
    export default function App() {
      const [checked, setChecked] = useState(false);
      const toggle = () => setChecked(!checked);
      return (
        <div className="App">
          <Label for="input" checked={checked}>
            <Input id="input" type="checkbox" onChange={toggle} />
          </Label>
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      • 2018-01-02
      • 2016-10-06
      • 2013-10-22
      • 2015-03-12
      相关资源
      最近更新 更多