javascript - 如何在反应中显示复选框的数量?该功能本身有效,但无法在应用程序中显示计数
问题描述
handleCheckCount 函数外的计数为 0,那么如何在 render 中传递标签中选中框的实际计数?我尝试将状态传递为选中的复选框总数:{this.state.count},但它只返回 0。如果我在 handleCheckCount 函数中使用 console.log(count),它会显示控制台中选中框的数量,但是外面它返回0。
state={
checked: false,
count: 0
}
handleCheckCount=()=> {
let input = document.getElementsByTagName('input');
let count= this.state.count
for (var i = 0; i < input.length; i++) {
if (input[i].type === "checkbox" && input[i].checked === true) {
count++
}
}
console.log(count)
}
render(){
return(
<div>
<table>
<thead>
<tr>
<th className="select_all">
<input type="checkbox" name="check" id="parent"
onClick={this.onSelectAll.bind(this)} onChange={this.handleCheckCount}/>
</th>
<th>Score</th>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
</table>
<h2>Total Number of Checkbox Selected: </h2>
</div>
)
}
解决方案
这是一个工作示例:
class App extends React.Component {
state={
checked: false,
count: 0
}
handleCheckCount=(e)=> {
// let input = document.getElementsByTagName('input');
const { checked, type } = e.target;
// let count= this.state.count
// for (var i = 0; i < input.length; i++) {
if (type === "checkbox" && checked === true) {
this.setState(state => state.count++, this.logCount)
} else {
this.setState(state => state.count--, this.logCount)
}
// }
}
logCount() {
console.log(this.state.count);
}
render(){
return(
<div>
<table>
<thead>
<tr>
<th className="select_all">
<input type="checkbox" name="check" id="parent" onChange={e => this.handleCheckCount(e)}/>
</th>
<th>Score</th>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
</table>
<h2>Total Number of Checkbox Selected: {this.state.count}</h2>
</div>
)
}
}
你的问题是你没有更新你的状态,只是count
函数内的作用域变量(你也记录了同一个)。我还添加了一个else
块来减少计数,并删除了onClick
侦听器。
更新:没有必要使用getElementsbyTagName
和 for 循环。您可以使用该事件来获取目标及其属性。
希望这可以帮助。
推荐阅读
- html - 找不到我的 html 页面
- java - 如何获得数组的两个峰值的最大值并使用 for 循环将它们带走?有任何想法吗?
- android - 在其他类中覆盖 onBackPressed
- reactjs - 我的滑块不工作并且没有显示错误并且所有图像都出现在页面上
- javascript - 使用不涉及 qualtrics 中嵌入数据的解决方法时,可以查看参与者的响应
- git - 如何在 Gitlab 中授予对特定 LDAP 用户的访问权限
- powershell - 组合字符串和变量会导致额外的空间
- primefaces - 如何自定义 Primefaces Schedule 的标题
- git - 我可以撤消在其他 git 分支中所做的更改吗?
- hybris - 没有名为 > 'mystoreBrandCategoryCodeValueProvider' 的 bean 可用 (hybris)