本文介紹了ReactJS實(shí)現(xiàn)表單的單選多選和反選的示例,分享給大家,希望對大家有所幫助。
需求是對列表實(shí)現(xiàn)單選,反選和多選,全部清除的操作
......  this.state = {   //初始化空數(shù)組,表示已經(jīng)選擇的   selectedStores:[],  }......handleClick(e){ const newSelection = e.target.value;//拿到點(diǎn)擊的具體一項(xiàng) let newSelectionArray;//新建一個(gè)空數(shù)組//判斷點(diǎn)擊項(xiàng)是否為選擇狀態(tài),是的話清除選中狀態(tài) if(this.state.selectedStores.indexOf(newSelection) > -1) {  newSelectionArray =  this.state.selectedStores.filter((s:any) => s !== newSelection)} else {//不是的話就加入新選擇數(shù)組  newSelectionArray =  [...this.state.selectedStores, newSelection];} this.setState({// 新選擇數(shù)組統(tǒng)一改為選中狀態(tài)  selectedStores: newSelectionArray });}Array.prototype.indexOf()方法返回在數(shù)組中可以找到一個(gè)給定元素的第一個(gè)索引,如果不存在,則返回-1。
語法:
arr.indexOf(searchElement)arr.indexOf(searchElement[, fromIndex = 0])
Array.prototype.filter()方法創(chuàng)建一個(gè)新數(shù)組, 其包含通過所提供函數(shù)實(shí)現(xiàn)的測試的所有元素。
語法:
var new_array = arr.filter(callback[, thisArg])
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答