【问题标题】:Search by name or ID with Material UI autocomplete使用 Material UI 自动完成功能按名称或 ID 搜索
【发布时间】:2020-12-05 18:52:22
【问题描述】:

我正在构建一个带有自动完成功能的搜索模式,我最终想要实现的是能够通过姓名或 ID 来搜索人们。但是当你从建议中选择一个人并且名字进入输入字段时,我不想显示 ID(原因是真实的 ID 会很长而且看起来很丑)。 这是一个截图,以便更好地理解问题

一旦我从建议中选择了一个选项,我不希望那个数字 6 出现。

这是我的自动完成代码

 <Autocomplete
        multiple
        id="tags-outlined"
        options={students}
        onInputChange={(event) => event.target}
        getOptionLabel={({ firstName, lastName, id }) =>
          `${firstName} ${lastName} ${id}`
        }
        filterSelectedOptions
        renderOption={({ firstName, lastName, id }) => {
          return (
            <div>
              <div>
                {`${firstName} `}
                {lastName}
              </div>
              <span>{id}</span>
            </div>
          );
        }}
        renderInput={(params) => (
          <TextField
            {...params}
            className={classes.input}
            variant="outlined"
            label="Name or Student ID"
          />
        )}
      />

【问题讨论】:

    标签: reactjs autocomplete material-ui


    【解决方案1】:

    您可以使用createFilterOptions 创建自定义过滤器并将其作为filterOptions 属性传递给Autocomplete

    在您的情况下,您必须提供stringify 配置,该配置控制如何将选项转换为字符串,以便它可以与输入文本片段匹配 - docs

    ...
    import Autocomplete, { createFilterOptions } from "@material-ui/lab/Autocomplete";
    
    const filterOptions = createFilterOptions({
      stringify: ({ firstName, lastName, id }) => `${firstName} ${lastName} ${id}`
    });
    
    function App() {
      return (
        <div>
          <Autocomplete
            multiple
            id="tags-outlined"
            options={students}
            onInputChange={(event) => event.target}
            filterOptions={filterOptions}
            getOptionLabel={({ firstName, lastName }) => {
              // this is how our option will be displayed when selected
              // remove the `id` here
              return `${firstName} ${lastName}`;
            }}
            filterSelectedOptions
            renderOption={({ firstName, lastName, id }) => {
              return (
                <div>
                  <div>
                    {`${firstName} `}
                    {lastName}
                  </div>
                  <span>{id}</span>
                </div>
              );
            }}
            renderInput={(params) => (
              <TextField
                {...params}
                variant="outlined"
                label="Name or Student ID"
              />
            )}
          />
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 2012-11-06
      相关资源
      最近更新 更多