【问题标题】:Change table background color when checkbox is ticked勾选复选框时更改表格背景颜色
【发布时间】:2022-02-06 00:38:17
【问题描述】:

我有这个渲染:

render() {
    const {policy} = this.props;
    return (
      <div className="my-content">
          <table className="checkbox-table">
              <label>
                <input className="checkbox-round" type="checkbox" onClick={this.onClickOfAgreement(pol)}/>
                &nbsp;&nbsp; Agree and access
              </label>
          </table>
      </div>   

这是我正在使用的 CSS:

.my-content {
  position: relative;
  background-color: #fefefe;
  padding: 0;
}

.checkbox-table {
  margin: 10px;
  border-radius: 7px;
  width: auto;
  padding: 10px;
}

.checkbox-round {
  width: 1.3em;
  height: 1.3em;
  background-color: white;
  border-radius: 50%;
  vertical-align: middle;
  border: 1px solid grey;
  appearance: none;
  -webkit-appearance: none;
  outline: none;
  cursor: pointer;
}

.checkbox-round:checked {
  background-color: #4f9f31;
  border-color: #fefefe;
  border-width: 3px;
}

我希望选中复选框时整个表格背景也变为#4f9f31。这是怎么做到的?

我尝试了Property 'value' does not exist on type 'Readonly<{}>'中的解决方案,但在我的浏览器中导致了这个错误:

“Readonly”类型上不存在属性“backgroundColor”

我添加了一个状态接口来解决错误,但随后得到了TypeError: Cannot read properties of null (reading 'backgroundColor')。我似乎错过了一些东西。 How to dynamically add a class to manual class names? 但它给了我

【问题讨论】:

标签: javascript css reactjs typescript


【解决方案1】:
<table className={`checkbox-table ${this.state.addBackgroundColor}`}>

要使其工作,您需要初始化一个名为addBackgroundColor 的状态。 然后,您的函数onClickOfAgreement(pol) 可以将状态背景颜色设置为“已选中”。 然后在 CSS 上制定一个规则,当状态为 checked 时添加背景颜色:

.checked {
  background-color: #4f9f31;
}

【讨论】:

  • 谢谢。我收到Property 'backgroundColor' does not exist on type 'Readonly&lt;{}&gt;。我认为我需要以某种方式对其进行初始化。
  • 当然需要初始化一个叫做backgroundColor的状态。如果你有一个类组件在你的构造函数中会是这样的:` state = { backgroundColor: }` Apoligies,因为你没有在问题中发布你的整个代码我也很短在我的回答中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
  • 1970-01-01
  • 2021-01-12
  • 2022-12-18
相关资源
最近更新 更多