【问题标题】:My checkbox does not stay checked once clicked (styling checkbox with css)单击后,我的复选框不会保持选中状态(使用 CSS 设置复选框样式)
【发布时间】:2020-02-25 18:32:19
【问题描述】:

我正在使用 React 和纯 CSS 来创建一个复选框列表并设置它们的样式。

如果没有样式,我的复选框可以完美运行,它会保持选中状态并注册正确的值。

但是,当我添加样式时,如果我点击一个复选框,“检查”不会保留。基本上,如果我悬停复选框,则会出现“检查”,但如果我单击它,则“检查”不会持续存在。

我的复选框组件

import React from 'react';
import '../mystyles/Dropdown.css'


function Jurisdictions(props) {
  const [selectedOpts, setSelectedOpts] = React.useState(new Set());

  function handleChange(event) {
    const value = event.target.value;
    const checked = event.target.checked;

    if (checked) {
      selectedOpts.add(value);

    } else {
      selectedOpts.delete(value);
    }

    setSelectedOpts(new Set(selectedOpts));
    props.onChange && props.onChange(Array.from(selectedOpts.values()));
  }

  return (
    <div className="dropdown-jurisdictions">
      {props.options.map((opt) => (
        <label className="item-list" key={opt}>
          {opt}
          <input
            type="checkbox"
            name="opts"
            value={opt}
            onChange={handleChange}
            className="my-checkbox"
          />
        </label>
      ))}
    </div>
  )
}


export default Jurisdictions;

我的 CSS 样式 - Dropdown.css

.dropdown-jurisdictions {
  overflow-y: auto;
  overflow-x: none;
  height: 170px;
  width: 300px;
  text-align: left;
  color: #3D5A80;
}




.my-checkbox {
  display: none;
}


label {
  display: inline-block;
  position: relative;
  padding-left: 25px;
  font-size: 16px;
  line-height: 20px;
  margin: 5px;
}
label:before {
  line-height: 20px;
  content: "";
  display: inline-block;
  width: 16px;
  height: 16px;
  position: absolute;
  left: 0;
  background-color: #ffffff;
  border: 1px solid #666666;
}

input[type=checkbox]:checked + label:before,
label:hover:before {
  content: "\2713";
  color: #666666;
  text-align: center;
  line-height: 16px;
}

我很确定问题出在我的 CSS 中,但我看不出原因。 可能是因为label和我的checkbox不在一个级别?

【问题讨论】:

    标签: css reactjs checkbox


    【解决方案1】:

    首先,您在input 上没有名为checked 的属性。我认为您需要先添加该属性。虽然我认为这仍然行不通,因为您正在做的样式是 sibling 而不是父母。

    你可以看到这个父元素选择器:Is there a CSS parent selector?

    希望这会有所帮助!

    【讨论】:

    • 这不是 React 问题。我的复选框工作正常,单击复选框时它不是持久的CSS。
    • 您在css 中使用checked,并且您没有在react 中传递该属性。另外,请查看第二部分,我添加了关于样式的注释。
    【解决方案2】:

    你的复选框组件应该有一个属性checked={this.props.checked} 或类似的东西来表明它处于选中状态。

    您的handleChange 函数应该反转stateprops 中的checked 变量的状态。

    【讨论】:

    • 这不是 React 问题。我的复选框工作正常,单击复选框时它不是持久的CSS。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 2016-06-19
    • 2012-10-23
    相关资源
    最近更新 更多