React中如何校验商品多组radio属性全部选中后再执行加入购物车操作
实现方案
步骤1:新增存储选中属性的state
在组件的state中新增selectedAttributes字段,用来存储每个属性组的选中值,初始为空对象:
// 初始化state时添加对应字段 this.state = { // 原有其他state(如product等)保留 selectedAttributes: {} }
步骤2:给单选按钮绑定选中更新事件
修改原有属性渲染代码,给radio添加onChange事件,用户选择时更新选中值,同时添加checked属性实现选中状态回显:
{this.state.product.attributes.map(attribute=>{ return ( <> <h5>{attribute.name.toUpperCase() + ":"}</h5> <> {attribute.items.map(item =>{ return ( <> <input onChange={()=>{ this.setState(prev => ({ selectedAttributes: { ...prev.selectedAttributes, [attribute.name]: item.value } })) }} type="radio" id={item.id + " " + attribute.name} name={attribute.name} value={item.value} checked={this.state.selectedAttributes[attribute.name] === item.value} /> <label htmlFor={item.id + " " + attribute.name}>{item.displayValue}</label> </> ) })} </> </> ) })}
步骤3:加购前添加校验逻辑
修改ADD TO CART按钮的点击事件,先校验所有属性组都已选中,再执行加购操作:
<button onClick={()=>{ // 校验所有属性组是否都有选中值 const allAttributeSelected = this.state.product.attributes.every(attribute => { return this.state.selectedAttributes.hasOwnProperty(attribute.name) }) if (!allAttributeSelected) { alert('请选择全部商品属性') return } // 校验通过后执行加购,可按需把选中属性一起传入方法 addProduct(this.props.id, this.state.product.prices, this.state.selectedAttributes) }}>ADD TO CART</button>
可选优化
如果想要降低用户操作成本,可以提前将未选全属性的按钮置灰:
// render方法内先计算是否全选 const isAllSelected = this.state.product.attributes.every(attr => this.state.selectedAttributes[attr.name]) // 按钮增加disabled属性 <button disabled={!isAllSelected} onClick={()=>{ addProduct(this.props.id, this.state.product.prices, this.state.selectedAttributes) }} >ADD TO CART</button>
内容的提问来源于stack exchange,提问作者asem shaat
相关产品推荐
相关产品推荐

