javascript - react js中带有标签的单选按钮
问题描述
大家好 !
今天,我正在尝试将诸如nike.com Air Force 1 产品页面之类的可选属性添加到购物车
我想选择一个项目并将单选按钮的值存储在一个状态中。
为此,我正在使用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”,我不知道是否是一个错误或者是否不是这样做的好方法。
解决方案
其他解决方案是传递所选项目的索引:
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}`}
推荐阅读
- python - 如何运行python代码的指定部分
- c# - 在 c# 中使用 MVVM (Model-View-ViewModel) 的 WPF OpenFileDialog
- javascript - 为什么这个 JS 函数返回错误的日期?
- excel - 如何借助 Excel 中的宏删除特定字符串
- django - 从 django 管理页面重新启动服务的选项
- c++ - 关于别名模板
- sql-server - 与 SQL Server 连接执行期间 vb.net 中的登录错误
- c++ - C++ 使用 qfile 写入资源文件(QIODevice::write (QFile,"x"): device not open)
- twitter-bootstrap - Bootstrap 4 Dropdown Navbar 使用 Plus 和 Minus Fontawesome 5 更改插入符号
- elasticsearch - Elasticsearch - 使用通配符的自定义词干覆盖