ReactJS实现表单的单选多选和反选的示例
本文介绍了ReactJS实现表单的单选多选和反选的示例,分享给大家,希望对大家有所帮助。
需求是对列表实现单选,反选和多选,全部清除的操作
...... this.state={ //初始化空数组,表示已经选择的 selectedStores:[], } ...... handleClick(e){ constnewSelection=e.target.value;//拿到点击的具体一项 letnewSelectionArray;//新建一个空数组 //判断点击项是否为选择状态,是的话清除选中状态 if(this.state.selectedStores.indexOf(newSelection)>-1){ newSelectionArray= this.state.selectedStores.filter((s:any)=>s!==newSelection) }else{ //不是的话就加入新选择数组 newSelectionArray= [...this.state.selectedStores,newSelection]; } this.setState({ //新选择数组统一改为选中状态 selectedStores:newSelectionArray }); }
Array.prototype.indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
语法:
arr.indexOf(searchElement) arr.indexOf(searchElement[,fromIndex=0])
Array.prototype.filter()方法创建一个新数组,其包含通过所提供函数实现的测试的所有元素。
语法:
varnew_array=arr.filter(callback[,thisArg])
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。