简体   繁体   English

如何在带有钩子的 ReactJS 中使用复选框作为单选按钮?

[英]How to use checkbox as Radio Button in ReactJS with hooks?

I'm Building a filter in ReactJS with hooks and now I need apply some style to the checkboxes.. The CSS is not the problem, I already did it in vanilla:我正在用钩子在 ReactJS 中构建一个过滤器,现在我需要对复选框应用一些样式.. CSS 不是问题,我已经在 vanilla 中做到了:

function checkOne(checkbox) {

    var checkboxes = document.getElementsByName('plan')

    checkboxes.forEach((item) => {

        item !== checkbox ? item.checked = false : item.checked = true;

    })

}

=======================================================================
                             X 3

                  <label for="premium">
                      <input 
                        type="checkbox" 
                        name="plan" 
                        onclick="checkOne(this)"
                        class="input-check" 
                        value="Premium"
                       >
                      <span 
                       class="checkmark" 
                       id="premium"
                      >
                         Premium
                     </span>           
                 </label>

Now I need to do the same think in react with hooks and I get stuck, I'm mapping a source of products and making a list of checkboxes form the product categories...现在我需要做同样的思考来对钩子做出反应,但我被卡住了,我正在映射产品来源并制作产品类别的复选框列表......

... 

const [checked, setChecked] = useState(false) //hook

...

handleChange(e, checkbox){
      setProduct(e.target.value);
      setSearch(e.target.value);      

 let checkboxes = document.getElementsByName('products')

    checkboxes.forEach((item) => {

        item !== checkbox ? setChecked(false) : setChecked(true);

    })
}

... in render method

      <div className="filters" id="top">
         {uniqueProduct.map(product => (    
             <label key={product.id}>
                <input
                      className='filters-available-size'
                      type="checkbox"
                      value={product.category}
                      onChange={handleChangeProduct} // <-- ?¿?¿ what should go here?
                      name='product'
                   />
                   <span className="checkmark">
                       {product.category}
                   </span>
             </label>
          ))}
        </div>

Why do you need to use checkboxes as radio buttons?为什么需要使用复选框作为单选按钮? I'm going to assume because of the styling--a design decision, perhaps.我要假设是因为造型——也许是设计决定。 In which case, I would use radio buttons for the functionality and then use CSS to hide radio buttons and show checkboxes that reflect the state of the chosen option.在这种情况下,我将使用单选按钮作为功能,然后使用 CSS 隐藏单选按钮并显示反映所选选项状态的复选框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM