如何动态添加isFixed如果项目长度是一个在反应选择?



我想做一个多过滤器,以便用户可以删除任何项目,直到项目长度为1。对于下面的例子,我想在用户从3个项目中删除2个时动态地在对象中添加isFixed = true。

import React, { useState } from 'react';
import Select from 'react-select';
const options = [
{ value: 'apple', label: 'Apple' },
{ value: 'orange', label: 'Orange' },
{ value: 'grape', label: 'Grape' },
];
const orderOptions = (values) =>
values && values.filter((v) => v.isFixed).concat(values.filter((v) => !v.isFixed));
export default function TestSelect() {
const [value, setValue] = useState(orderOptions([...options]));
console.log('value', value);
const onChange = (value, { action, removedValue }) => {
switch (action) {
case 'remove-value':
case 'pop-value':
if (removedValue.isFixed) {
return;
}
break;
case 'clear':
value = options.filter((v) => v.isFixed);
break;
default:
break;
}
value = orderOptions(value);
setValue(value);
};
return (
<div>
<Select
value={value}
isMulti
isClearable={value && value.some((v) => !v.isFixed)}
name="fruit"
classNamePrefix="select"
onChange={onChange}
options={options}
defaultValue={options}
/>
</div>
);
}

您只需要检查在switch-case中values数组中是否只剩下一个元素。为此,只需添加两行:

...
const onChange = (value, { action, removedValue }) => {
switch (action) {
case "remove-value":
case "pop-value":
if (removedValue.isFixed) return;
if (value.length === 1) value[0].isFixed = true; // <-- add the isFixed element
break;
case "clear":
value = options.filter((v) => v.isFixed);
break;
default:
value.forEach(x => x.isFixed = false) // <-- remove the isFixed element
break;
}
value = orderOptions(value);
setValue(value);
};
...

记得添加styles部分,使其更直观。如你所见

最新更新