从所选项目中删除项目时如何捕获react-select中的删除事件?

问题描述 投票:0回答:5

首先,感谢您所做的出色工作。这对我来说更容易。那么在这里我想捕获删除事件,我该怎么做呢?我阅读了文档,但找不到删除事件

reactjs react-select
5个回答
9
投票

我认为他们没有为此举办活动。他们只有

onChange

因此,要检测某个选项是否被删除,您必须将当前状态与

onChange
发出的新值进行比较。

示例:

handleOnChange(value) {
  let difference = this.state.selected.filter(x => !value.includes(x)); // calculates diff
  console.log('Removed: ', difference);                         // prints array of removed

  this.setState({ selected: value });
}
render() {
  return (
    <div>
      <Select
        multi={this.state.multi}
        options={this.state.options}
        onChange={this.handleOnChange.bind(this)}
        value={this.state.selected}
        showNewOptionAtTop={false}
      />
    </div>
  );
}

演示:https://codesandbox.io/s/7ymwokxoyq


5
投票

React Select 通过 props 向您公开各种事件监听器。 onchange 函数属性现在具有以下签名。 (值:ValueType,操作:ActionType)。

因此,您可以获得这些事件: select-optiondeselect-optionremove-valuepop-valueset-valueclearcreate-option,通过它们可以处理创建和删除。

请参阅文档


1
投票

他们没有任何活动。我面临着同样的问题,但就我而言,我需要

added
removed
项目。如果有人想要这两个值

import 'difference' from 'lodash/difference'
this.currentTags = []
handleChange = (options) => {
    const optionsValue = options.map(({ value }) => value)
    if (this.currentTags.length < options.length) {
      const addedElement = difference(optionsValue, this.currentTags)[0]
      this.currentTags.push(addedElement)
      console.log("addedElement",addedElement)
      //call custom add event here
    }
    else {
      let removedElement = difference(this.currentTags, optionsValue)[0]
      console.log("removedElement", removedElement)
      // call custom removed event here
      let index = this.currentTags.indexOf(removedElement)
      if (index !== -1) {
        this.currentTags.splice(index, 1)
      }
    }
  }

1
投票

这段代码可以让我知道是否有任何项目被删除 我在重新选择中的 onChange 事件上调用句柄更改函数

const [selectedGroups, setSelectedGroups] = useState([]);
const handleChange = (value) => {

const diifer = value.length <= selectedGroups.length;
if(diifer){
// item is removed 
}
var arr = value.map((object) => object.value);
setSelectedGroups(arr);

};

0
投票

他们在 onChange 事件上有一个参数给我们带来了两件事

  1. 新价值
  2. 动作元

actionMeta 看起来像这样

{ "action": "删除值", “已删除的值”:{ “值”:“bb1e0dff-084e-4c2d-a5a7-0ba485bd2954”, "label": "标签示例" }, "name": "示例名称" }

© www.soinside.com 2019 - 2024. All rights reserved.