在react-select https://github.com/jedwatson/react-select中,我们可以以编程方式删除react-select中的选定选项之一吗?
例如,在下面的屏幕截图中,我想以red编程方式取消选择?
非常感谢!
您可以将选定的选项保存在状态中,并通过更新新状态来删除选定的选项,您可以在此处查看codeSandBox
import React, { useState } from "react";
import "./styles.css";
import Select from "react-select";
const options = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
];
export default function App() {
const [selectedOption, setSelect] = useState(null);
const handleChange = selectedOption => {
setSelect(selectedOption);
};
const removeOption = e => {
const newSelect = selectedOption.filter(
item => item.value !== e.target.name
);
setSelect(newSelect);
};
return (
<>
<Select
isMulti
value={selectedOption}
onChange={handleChange}
options={options}
/>
<button name="chocolate" onClick={removeOption}>
Remove Chocolate
</button>
<button name="vanilla" onClick={removeOption}>
Remove Vanilla
</button>
<button name="strawberry" onClick={removeOption}>
Remove Strawberry
</button>
</>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11203 次 |
| 最近记录: |