React Tag Autocomplete:如何从建议中删除所选标签

时间:2019-08-20 07:28:38

标签: reactjs

你好,我使用了react标签的自动完成功能。 请告诉我如何从建议列表中删除所选标签。

这是react标签自动完成的链接。

https://www.npmjs.com/package/react-tag-autocomplete

1 个答案:

答案 0 :(得分:0)

您必须在react状态下管理建议和所选标签变量。

这里我以git仓库中给出的示例为例,并更新了两种方法( handleDelete handleAddition )。

import React, { Component } from 'react';
import ReactTags from 'react-tag-autocomplete';

class ReactTag extends Component {

  constructor(props) {
    super(props)

    this.state = {
      tags: [
        { id: 1, name: "Apples" },
        { id: 2, name: "Pears" }
      ],
      suggestions: [
        { id: 3, name: "Bananas" },
        { id: 4, name: "Mangos" },
        { id: 5, name: "Lemons" },
        { id: 6, name: "Apricots" }
      ]
    }
  }

  handleDelete(i) {
    if (i === -1) return false;
    const tags = this.state.tags.slice(0)
    tags.splice(i, 1);
    const removedTag = this.state.tags[i];
    const suggestions = [].concat(this.state.suggestions, removedTag);
    this.setState({ tags, suggestions })
  }

  handleAddition(tag) {
    const tags = [].concat(this.state.tags, tag);
    const suggestions = this.state.suggestions.filter(x => x.id !== tag.id);
    this.setState({ tags, suggestions })
  }

  render() {
    return (
      <ReactTags
        tags={this.state.tags}
        suggestions={this.state.suggestions}
        handleDelete={this.handleDelete.bind(this)}
        handleAddition={this.handleAddition.bind(this)} />
    )
  }

}

export default ReactTag;