在 React 中,有没有办法更改选中的单选输入上父 Label 标签的背景颜色?

In React Is there a way to change the background color of a parent Label tag on a Radio Input checked?

我正在使用 React 语义 UI。在 css 中,我试图更改输入的父标签的背景颜色,因此当单击单选按钮时它会更改颜色。我隐藏了显示 none 的单选按钮。因为标签给它一个漂亮的按钮外观。这是我的代码。在 html 中,我只是使用了一个输入标签并更改了跨度,但必须使用反应语义 ui 库以不同的方式完成。我能够像我的 html 版本一样使用输入和跨度,但在这种情况下,点击功能不起作用。

这是一个 CodeSandbox,其中加载了 React Semantic Ui 库,它实现了第一个答案,但不起作用。 https://codesandbox.io/s/kind-tereshkova-u9toz?fontsize=14

我添加了 "Compiled" html

<Segment>
    <Menu attached="top" borderless={true}>
        <Menu.Item>
            <Header>
                 Scale:
            </Header>
            <Label className="filter_check" size="large">
                 <Form.Field
                     label="Year"
                     control='input'
                     type='radio'
                     name='year'
                 />
            </Label>
        </Menu.Item>
    </Menu>
</Segment>
.filter_check input {
    display: none;
}
input:checked + .filter_check>.label {
    background: #00b5ad !important;
    width: 100% !important;
}

.field input[type=radio]:checked + label {
    background: red;
    color: #fff;
    margin-left: 1em;
    padding: .3em .78571429em;
}

"complied" html

<div class="ui segment">
   <div class="ui borderless top attached menu">
      <div class="item">
         <div class="ui header">Scale:</div>
         <div class="ui large label filter_check">
            <div class="field"><label><input name="year" type="radio"> Year</label></div>
         </div>
      </div>
   </div>
</div>

查看 SandBox 后,我能够看到 React 代码编译为以下 HTML:

<div class="ui large label filter_check">
  <div class="field">
  <label>
  <input name="year" type="radio"> Year
  </label>
  </div>
</div>

然后我认为您想在单击 input 字段时修改 parent 元素。这不是微不足道的,需要修改父元素,我使用 <Form.Field>:

onChange 道具进行了修改
<Label className="filter_check" size="large">
    <Form.Field
        label="Year"
        control="input"
        type="radio"
        name="year"
        onChange={checkInput}
    />
</Label>

使用以下函数,将 checked class 添加到修改后的元素:

function checkInput(e) {
    let labelElement = e.target.parentNode;
    let bgElement = labelElement.parentNode.parentNode;
    bgElement.classList.add('checked');
}

然后我们用以下内容更新 CSS:

div.ui.large.label.filter_check.checked {
    background-color: red;
}

还有 - Voilà!