This article mainly introduces examples of single-selection, multi-selection and reverse selection in ReactJS implementation forms. It is of great practical value. Friends in need can refer to it.
This article introduces the single-selection and multi-selection implementation of forms in ReactJS. I would like to share with you examples of reverse selection and hope it will be helpful to you.
The requirement is to implement single selection, reverse selection, multi-selection, and all clear operations on the list
...... this.state = { //初始化空数组,表示已经选择的 selectedStores:[], } ...... handleClick(e){ const newSelection = e.target.value;//拿到点击的具体一项 let newSelectionArray;//新建一个空数组 //判断点击项是否为选择状态,是的话清除选中状态 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 }); }
The Array.prototype.indexOf() method returns the first index where a given element can be found in the array , if it does not exist, returns -1.
Syntax:
arr.indexOf(searchElement) arr.indexOf(searchElement[, fromIndex = 0])
The Array.prototype.filter() method creates a new array containing all elements of the test implemented by the provided function.
Grammar:
var new_array = arr.filter(callback[, thisArg])
The above is the detailed content of How to implement single-select, multiple-select and reverse-select in forms in ReactJS. For more information, please follow other related articles on the PHP Chinese website!