首页 > 解决方案 > react js中带有标签的单选按钮

问题描述

大家好 !

今天,我正在尝试将诸如nike.com Air Force 1 产品页面之类的可选属性添加到购物车

我的问题是这样的: 捕获-d-cran-2020-10-19-12-57-35.png

我想选择一个项目并将单选按钮的值存储在一个状态中。

为此,我正在使用useRef

const getValueFromRadio = React.useRef(null)

为了调用这个引用我onClick(myFunction)在标签标签上使用

<h1 className="text-center text-2xl">{product.name}</h1>
<div>
    <div className={'block my-3'}>
        {product.attribute !== undefined ? product.attribute.map((item, index) => <div className={'inline-block'} key={index}>
        <label onClick={labelOnclickHandler} className="cursor-pointer py-2 px-3 my-3 mx-2 border border-grey-500 hover:border-black h-3 rounded" htmlFor={item.id}>{item.value}</label>
        <input className="hidden" ref={getValueFromRadio} type="radio" id={item.id} value={item.value} name={'selectSize'}/>
              </div>)
         : null}
     </div>
</div>

// sorry for the piss of shit indentation.

如果我只有一个属性引用将获得S大小,并且我存储在我的状态中的值是 S:

const labelOnclickHandler = (e) => {
        const el = e.target.classList
        if (el.contains('border-grey-500')){ //toggling.
            el.remove('border-grey-500')
            el.add('border-black')
        } else {
            el.add('border-grey-500')
            el.remove('border-black')
        }
        setPrevElement(el) // get preview el for remove the border black.
        setSelectSize(getValueFromRadio.current.value) // state to cart.
}

但是如果我有多个属性,反应或引用每次都会返回我“M”,我不知道是否是一个错误或者是否不是这样做的好方法。

标签: javascriptreactjs

解决方案


其他解决方案是传递所选项目的索引:

  const labelOnclickHandler = (e, index) => {
    const el = e.target.classList
    if (el.contains('border-grey-500')){ //toggling.
        el.remove('border-grey-500')
        el.add('border-black')
    } else {
        el.add('border-grey-500')
        el.remove('border-black')
    }
    setPrevElement(el) // get preview el for remove the border black.
    setSelectSize(product.attribute[index].value) // state to cart.
}

而且你不需要使用 ref:

<div>
        <div className={"block my-3"}>
          {product.attribute !== undefined
            ? product.attribute.map((item, index) => (
                <div className={"inline-block"} key={index}>
                  <label
                    onClick={(e)=> labelOnclickHandler(e, index)}
                    className="cursor-pointer py-2 px-3 my-3 mx-2 border border-grey-500 hover:border-black h-3 rounded"
                    htmlFor={item.id}
                  >
                    {item.value}
                  </label>
                  <input
                    className="hidden"
                    type="radio"
                    id={item.id}
                    value={item.value}
                    name={"selectSize"}
                  />
                </div>
              ))
            : null}
        </div>
      </div>

我建议您避免使用索引作为键值 (key={index})。更多信息在这里https://reactjs.org/docs/lists-and-keys.html

也许你可以使用key={`product_attribute_${index}`}


推荐阅读