首页 > 解决方案 > 如何更改 react-bootstrap 中活动单选按钮的背景颜色?

问题描述

在一个 React 项目中,我有单选按钮来列出日历日期和日期。我的意图是更改这些单选按钮的背景颜色并保留它。单击屏幕时它不应消失。

以下是供参考的代码:

{newDate.map((data, i) => (
          <ButtonGroup toggle style={{ width: "100%" }}>
            <GridListTile style={gridListStylePhoto}>
              <h5>{currday(data.getDay())}</h5>
              <ToggleButton
                key={i}
                type="radio"
                active="true"
                variant="light"
                name="radio"
                value={currday(data.getDay()) + " " + data.getDate()}
                checked={radioValue === data.getDate()}
                onChange={(e) => {
                  handleChange(e);
                }}
              >
                <br />
                {data.getDate()}
              </ToggleButton>
            </GridListTile>
          </ButtonGroup>
        ))}

以下是样式参考:

input[type="checkbox"],
input[type="radio"] {
  display: none;
}
.btn-light {
  background-color: transparent;
  border: transparent;
}

.btn-light:checked {
  background-color: red // Here is color doesn't change
}

为了改变上述单选按钮的背景颜色可以做些什么?

请参考下面的 Codesandbox 链接。

Codesandbox 链接:https ://codesandbox.io/s/material-demo-forked-hcbxl

标签: cssreactjs

解决方案


您可以使用现有的 onChange 事件切换每个单选按钮的类。

const handleChange = (e) => {
    const newData = e.target.value;
    var elems = document.querySelectorAll(".toggleButtonNew.active");
    [].forEach.call(elems, function (el) {
      el.classList.remove("active");
    });
    e.target.closest("label").classList.toggle("active");
    setRadioValue(newData);
};

并将您想要的样式添加到该类

.active {
    background-color: red !important;
}

推荐阅读