简体   繁体   English

从所选项目中删除和删除项目时,如何在反应选择中捕获添加和删除事件?

[英]How to catch add and remove event in react-select when andding and removing item from selected?

handleChange(value) {
    let difference = this.state.selected.filter(x => !value.includes(x));
    console.log("Removed: ", difference);
    this.setState({
        selected: value
    });
}

To get notified about addition of values in react-select, i used onKeyDown prop.为了获得有关在 react-select 中addition值的通知,我使用了onKeyDown道具。 This method( handleKeyDown ) will be called when user enters any manual value and hits enter or tab to add values like below:当用户输入任何手动值并按entertab添加如下值时,将调用此方法( handleKeyDown ):

      <Select
        inputValue={inputValue}
        isClearable={false}
        isMulti
        onChange={this.handleChange}
        onInputChange={this.handleInputChange}
        onKeyDown={this.handleKeyDown}
        placeholder="Type something and press enter..."
        value={value}
      />

    handleKeyDown = event => {
    const { inputValue, value } = this.state;
    if (!inputValue) return;
    console.log("event.key:", event.key);
    switch (event.key) {
      case "Enter":
        const newValues = inputValue.split(",").map(x => createOption(x));
        this.setState({
          inputValue: "",
          value: [...value, ...newValues]
        });
        event.preventDefault();
        break;
      case "Tab":
        this.setState({
          inputValue: "",
          value: [...value, createOption(inputValue)]
        });
        event.preventDefault();
        break;
      default:
        console.log("Other events caught");
    }
  };

You can capture remove event using onChange prop.您可以使用onChange道具捕获remove事件。 Below code shows that:下面的代码表明:

handleChange = (value, actionMeta) => {
    console.group("Inside handleChange");
    console.log(value);
    console.log(`action: ${actionMeta.action}`); // will capture remove event
    this.setState({ value });
  };

You can experiment in below sandbox.您可以在下面的沙箱中进行实验。 Above mentioned example is present in Sandbox: https://codesandbox.io/s/react-codesandboxer-example-7r2y6上面提到的例子存在于沙箱中: https : //codesandbox.io/s/react-codesandboxer-example-7r2y6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM