简体   繁体   English

自动完成选项在 React MaterialUI 中没有被删除

[英]Option from Autocomplete aren't getting removed in React MaterialUI

I am beginner in ReactJS and currently working with Material UI Autocomplete component.我是 ReactJS 的初学者,目前正在使用 Material UI Autocomplete组件。 I have a data object with keys as table name and columns as their value;我有一个data object ,其中键作为table namecolumns作为它们的值; an array of objects called columnData (is populated from values of data ) with field, ifSelected as its attributes, and field attribute used to set the option label of Autocomplete (which are rendered as Chip ).一个名为columnData的对象数组(由data的值填充),具有field, ifSelected作为其属性,以及用于设置Autocomplete选项 label 的field属性(呈现为Chip )。 When an option is selected in Autocomplete dropdown then corresponding ifSelected attribute is set to true .当在Autocomplete下拉列表中选择一个选项时,相应ifSelected属性设置为true However, problem comes when columnData object changes when a user selects different table name from data object and its corresponding value is assigned to columnData , in which previously selected option label isn't getting removed even when ifSelected attribute of all the option is false .但是,当用户从data object 中选择不同的table name并将其对应的值分配给columnData时, columnData false发生更改,并且先前选择的选项ifSelected的所有选项都没有被删除时,都会出现问题。

I went through material-ui docs here and tried fixing it using getOptionSelected prop but faced issue with deletion of chips (ie options) with that.我在这里浏览了material-ui文档并尝试使用getOptionSelected属性修复它,但遇到了删除chips (即选项)的问题。

Following is my code:-以下是我的代码:-

import React, { Component } from "react";
import { Chip, TextField } from "@material-ui/core";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default class MultiSelect extends Component {
  state = {
    table: "",
    tableData: [],
    data: {
      table1: ["col1", "col2", "col3", "col4", "col5"],
      table2: ["cola", "colb", "colc", "cold", "cole"]
    },
    columnData: []
  };

  handleTableChange = (event, value) => {
    console.log("Table change value is ", value);
    if (this.state.data[value]) {
      let columnData = this.state.data[value].map((column) => ({
        field: column,
        ifSelected: false
      }));
      console.log("Table change value is ", columnData);
      this.setState({ table: value, columnData });
    }
  };

  handleColumnChange = (columns) => {
    let data = this.state.columnData;

    if (data && columns) {
      data.forEach((column) => (column.ifSelected = false));
      console.log("Columns are ", columns);
      for (let column of columns) {
        let index = data.findIndex((item) => item.field === column.field);
        console.log("index is ", index);
        if (index !== -1) data[index].ifSelected = true;
      }
      this.setState({ columnData: data });
    }
  };

  componentDidMount() {
    let tableData = Object.keys(this.state.data);
    this.setState({ tableData });
    this.handleTableChange("table1");
  }

  render() {
    return (
      <>
        <Autocomplete
          id="table"
          options={this.state.tableData}
          getOptionLabel={(option) => option}
          renderInput={(params) => (
            <TextField {...params} variant="outlined" margin="normal" />
          )}
          value={this.state.table}
          onChange={this.handleTableChange}
        />
        <Autocomplete
          disabled={!this.state.table}
          style={{ marginTop: "1rem" }}
          multiple
          disableCloseOnSelect
          limitTags={3}
          options={this.state.columnData}
          getOptionLabel={(option) => option.field}
          renderInput={(params) => (
            <TextField
              style={{ fontWeight: "700" }}
              {...params}
              variant="outlined"
            />
          )}
          renderTags={(value, getTagProps) =>
            value.map((option, index) => (
              <Chip
                variant="outlined"
                key={option}
                label={option.field}
                {...getTagProps({ index })}
              />
            ))
          }
          onChange={(event, newValues) => this.handleColumnChange(newValues)}
        />
      </>
    );
  }
}

Would appreciate any hint.将不胜感激任何提示。 I have added demo here在这里添加了演示

You can fix the issue by passing the value prop to select the columns with ifSelected set to true .您可以通过将value属性传递给 select 将ifSelected设置为true的列来解决此问题。

<Autocomplete
  value={this.state.columnData.filter((column) => column.ifSelected)}
  // other props
/>

CodeSandbox 代码沙盒

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

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