现场工作示例:https ://react-3gte8y.stackblitz.io/
代码:https ://stackblitz.com/edit/react-3gte8y?file=src/App.js
首先让您的选项数组只包含数字:
const options = [1, 2, 3, 4, 5];
然后在您的 onChange 处理程序函数中检查所选值是否已经存在于 nums 状态,如果不存在则添加它,否则将其删除怎么办?使用方法轻松获取值的索引indexOf,如果返回 -1 表示num数组中不存在数字,否则 indexOf 将返回您选择的数字的实际索引:
const handleArrChange = ({ target }) => {
setNum((prev) => {
//get index of actual target.value
const index = prev.indexOf(target.value);
/*if index === -1 means not exist in array will return the prev
state and appending new chosen value*/
if (index === -1) {
return [...prev, target.value];
}
/* else (value exist) use splice to remove the chosen value from
the array */
prev.splice(index, 1);
/* don't use return prev, React will not detect changes in your
state and will not re render it */
return [...prev];
});
};
prev 是前一个状态,它在对 num 状态进行任何更改之前保持实际状态。
现在对您的 JSX 进行一些更改,首先不要忘记键,并确保将默认选择值设置select为禁用选项:
<select onChange={handleArrChange} value={"select"}>
<option disabled>select</option>
{options.map((option) => (
<option key={option}>{option}</option>
))}
</select>
和
{nums.map((num) => (
<p key={num}>{num}</p>
))}
现在您需要做的一件事是全选并取消全选
首先将所有选项添加到您的选项中:
<select onChange={handleArrChange} value={"select"}>
<option disabled>select</option>
<option>All</option>
{options.map((option) => (
<option key={option}>{option}</option>
))}
</select>
然后在 onChange 函数处理程序中检查是否是 All 被检查:
if(target.value === "All"){
if(nums.length > 0 ){
setNum([])
}else{
setNum(options)
}
return
}
此代码必须是您在选择值更改时首先执行的操作,将其添加到 onChange 函数的顶部:
这是完整的工作代码:
import React, { useState } from "react";
const options = [1, 2, 3, 4, 5];
export default function App() {
const [nums, setNum] = useState([]);
const handleArrChange = ({ target }) => {
if(target.value === "All"){
if(nums.length > 0 ){
setNum([])
}else{
setNum(options)
}
return
}
setNum((prev) => {
const index = prev.indexOf(target.value);
if (index === -1) {
return [...prev, target.value];
}
prev.splice(index, 1);
return [...prev];
});
};
return (
<div className="App">
<select onChange={handleArrChange} value={"select"}>
<option disabled>select</option>
<option>All</option>
{options.map((option) => (
<option key={option}>{option}</option>
))}
</select>
{nums.map((num) => (
<p key={num}>{num}</p>
))}
</div>
);
}