【问题标题】:Material UI creatable multi-select材质 UI 可创建多选
【发布时间】:2021-06-04 23:58:53
【问题描述】:

我正在尝试制作一个也可以使用 Material UI 创建的多选组件,但我无法从文档中弄清楚如何做到这一点。 autocomplate documentation page

以下示例是一个多选组件,如果我在键盘上单击 Enter,它会添加新值,但它不会告诉用户他可以添加该新值。但是,即使在这种情况下,我也不确定如何访问新的选定选项数组。

<Autocomplete
  multiple
  id="tags-filled"
  options={top100Films.map(option => option.title)}
  defaultValue={[top100Films[13].title]}
  freeSolo
  renderTags={(value, getTagProps) =>
    value.map((option, index) => (
      <Chip
        variant="outlined"
        label={option}
        {...getTagProps({ index })}
      />
    ))
  }
  renderInput={params => (
    <TextField
      {...params}
      variant="filled"
      label="freeSolo"
      placeholder="Favorites"
    />
  )}
/>

我发现另一个示例建议使用 filterOptions 属性添加新值,但由于某种原因,它不适用于之前的组件。

filterOptions={(options, params) => {
  const filtered = filter(options, params);

  // Suggest the creation of a new value
  if (params.inputValue !== "") {
    filtered.push({
      inputValue: params.inputValue,
      title: `Add "${params.inputValue}"`
    });
  }

  return filtered;
}}

这是我提到的示例的代码框: codesandbox example

所以我想要实现的是通过显示一个选项让用户添加新值并访问最终的选项数组来创建多选组件。

非常感谢您的帮助。

【问题讨论】:

  • 你有没有做到这一点?如果有,你愿意分享吗?

标签: reactjs material-ui


【解决方案1】:

虽然这可能无法解决您的确切需求 - 它确实允许您捕获值并按回车键创建遵循 gmail 电子邮件添加功能的芯片。

/* eslint-disable no-use-before-define */
import React from "react";
import Chip from "@material-ui/core/Chip";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";

const useStyles = makeStyles((theme) => ({
  root: {
    width: 500,
    "& > * + *": {
      marginTop: theme.spacing(3)
    }
  }
}));

export default function Tags() {
  const classes = useStyles();

  const handleChange = (x, emails) => console.log(x, emails);

  return (
    <div className={classes.root}>
      <Autocomplete
        multiple
        id="tags-filled"
        onChange={handleChange}
        options={[]}
        defaultValue={""}
        freeSolo
        renderTags={(value, getTagProps) =>
          value.map((option, index) => (
            <Chip label={option} {...getTagProps({ index })} />
          ))
        }
        renderInput={(params) => (
          <TextField
            {...params}
            variant="outlined"
            label="Emails"
            placeholder="Add Email"
          />
        )}
      />
    </div>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-15
    • 2020-11-26
    • 1970-01-01
    • 2021-09-06
    • 2021-05-27
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多