可以使用Antd中Select组件的onDeselect属性,该属性在用户取消选择某个选项时被调用。我们可以在该函数中更改Select组件的数据源,以从Select组件中移除选中的元素。
以下是一个示例代码:
import { Select } from 'antd';
const { Option } = Select;
class Demo extends React.Component {
state = {
options: ['Apple', 'Banana', 'Orange'],
selectedOptions: [],
}
handleDeselect = (value) => {
const { options, selectedOptions } = this.state;
const optionIndex = options.findIndex(option => option === value);
const selectedOptionIndex = selectedOptions.findIndex(option => option === value);
if (optionIndex >= 0 && selectedOptionIndex >= 0) {
const newOptions = [...options.slice(0, optionIndex), ...options.slice(optionIndex + 1)];
const newSelectedOptions = [...selectedOptions.slice(0, selectedOptionIndex), ...selectedOptions.slice(selectedOptionIndex + 1)];
this.setState({
options: newOptions,
selectedOptions: newSelectedOptions
});
}
}
render() {
const { options, selectedOptions } = this.state;
return (
);
}
}
在上述示例代码中,我们在Select组件上设置了onDeselect属性,并在选项被取消选择时调用handleDeselect函数。在该函数中,我们使用JavaScript的findIndex函数查找要删除的选项的索引,并使用slice函数从options和selectedOptions数组中移除选中的选项。最后,我们使用setState函数更新组件的状态,以反映更新后的数据源。