javascript - 如何取消选中禁用的单选按钮?反应.js
问题描述
`
import React from 'react'
import {withRouter} from 'react-router-dom'
import './Size.style.scss'
class Size extends React.Component {
constructor(props) {
super(props);
this.checkboxRef = React.createRef();
}
componentDidUpdate(prevProps) {
if (
this.props.location.search !== prevProps.location.search &&
this.checkCategoryChanges(this.props.location.search, prevProps.location.search) &&
this.checkboxRef.current.checked
){
this.checkboxRef.current.checked = false;
}
}
checkCategoryChanges (currentUrl, prevUrl) {
let items = currentUrl.charAt(0) === '?' ? currentUrl.slice(1).split('&') : currentUrl.split('&');
for(const item of items) {
if(
(item.indexOf('categories') !== -1 && prevUrl.indexOf(item) === -1) ||
(item.indexOf('categories') !== -1 && items.length === 1 )
) {
return true;
}
}
return false;
}
isChecked(e) {
if(this.props.isChecked) {
if(e.checkboxRef.current && e.checkboxRef.current.checked === false) {
// e.checkboxRef.current.checked = true;
this.runOnChange(true);
return true;
}
}
const mainUrlAsArray = window.location.href.split('?');
if(mainUrlAsArray.length === 2) {
const url = mainUrlAsArray[1];
let checkedItems = url.charAt(0) === '?' ? url.slice(1).split('&') : url.split('&');
for(const item of checkedItems) {
if(item.indexOf(this.props.urlKey) !== -1 && item.split('=')[1].indexOf(this.props.value) !== -1) {
return true;
}
}
return false;
}
}
runOnChange(e) {
const checkboxData = {
value: this.props.value,
urlKey: this.props.urlKey,
isChecked: e,
type: this.props.type ? this.props.type : 'checkbox'
}
this.props.onChange(checkboxData);
}
render() {
return (
<>
<label className="size-label">
<input
ref = {this.checkboxRef}
defaultChecked={this.isChecked(this) ? true : undefined}
value={this.props.value}
onChange={(e) => this.runOnChange(e.target.checked)}
type={this.props.type ? this.props.type : 'checkbox'}
className="size-radio"
name="size"
disabled={this.props.disabled}
/>
<span className="size-button size-2">{this.props.label}</span>
</label>
</>
)
}
}
export default withRouter(Size)
`我有一个单选按钮代表产品尺寸。我为第一个单选按钮添加了默认检查。并增加了产品尺寸的数量。如果产品尺寸数量为 0,我添加 disabled={true}。但是有一个问题,如果我的产品数量的第一个尺寸是 0,它仍然被检查。如果第一个单选按钮被禁用,我想为下一个单选按钮添加默认检查?但我无法解决这个问题。谁能帮帮我吗 ?
{this.state.colorData.map((size,index) =>
<Size
onChange={(e) => this.setState({size: e.value})}
key={index}
type="radio"
value={size.variation}
label={size.variation}
isChecked={index === 0 && this.state.size === ''}
disabled={size.qty ? false : true }
/>
)}
解决方案
推荐阅读
- c++ - VS2015/VC++ 在新的类模板中禁用默认 #include "stdafx.h"
- node.js - Joi 验证:最小长度功能不起作用
- mysql - 不为空但仍然得到“字段'日期'没有默认值”
- linux - 如何配置 xorg.conf ubuntu
- python - 哪个python画布API的线条质量最好?
- wordpress - 无法通过 AWS 上的 Bitnami Wordpress 登录
- python - 使用熊猫将列值转换为行
- node.js - io 在客户端未定义
- python - 使用regx python对两个字符之间的任何内容进行分组
- c# - ASP.NET Core 中的新任务如何利用依赖注入?