通过另一个参数自动完成搜索

发布于 2025-01-29 01:40:35 字数 686 浏览 4 评论 0原文

在下面的示例中, -

https://codesandbox.io/s/g5ucdj?file= /demo.tsx

我想实现功能,以便如果我有数组 -

const top100Films = [
  { title: 'The Shawshank Redemption', year: 1994 },
  { title: 'The Godfather', year: 1972 },
  { title: 'The Godfather: Part II', year: 1994 },]

然后,在我通过年度搜索时,我应该获得标题的标签选项。 例如。如果我在搜索框中输入1994年,我应该获得两个选择的标题选项 -

The Shawshank Redemption
The Godfather: Part II

我尝试了更改选项 -

options={top100Films.map((option) => option.year)}

但是通过此,我将获得一年作为我想要作为选项的选项,将年份输入文本框中。

In below example , -

https://codesandbox.io/s/g5ucdj?file=/demo.tsx

I want to achieve functionality such that , If I have array -

const top100Films = [
  { title: 'The Shawshank Redemption', year: 1994 },
  { title: 'The Godfather', year: 1972 },
  { title: 'The Godfather: Part II', year: 1994 },]

Then , in autocomplete when I search via year , I should get label options for title.
Eg. If I enter year 1994 in search box , I should get two title options for selection -

The Shawshank Redemption
The Godfather: Part II

I tried changing option -

options={top100Films.map((option) => option.year)}

But through this I get year as a option which I want title as a option , having year entered in text box.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫卆 2025-02-05 01:40:35

您可以使用mui createFilterOptions

import { createFilterOptions } from '@mui/material/Autocomplete';

声明过滤器,

const filterOptions = createFilterOptions({
  matchFrom: 'any',
  stringify: (option) => option.year.toString(),  //.toString because year is integer
});

然后在您的自动完成标签中添加以下添加以下:

filterOptions={filterOptions}

codesandbox 示例

该代码在JavaScript中,您可以相应地更改为打字稿。对于打字稿,请按照此 link

You can use MUI createFilterOptions

import { createFilterOptions } from '@mui/material/Autocomplete';

Declare filterOptions

const filterOptions = createFilterOptions({
  matchFrom: 'any',
  stringify: (option) => option.year.toString(),  //.toString because year is integer
});

Then in you Autocomplete tag add this:

filterOptions={filterOptions}

Codesandbox example.

The code is in javascript, you can change to typescript accordingly. For typescript follow this link

梦与时光遇 2025-02-05 01:40:35

当我看到您正在使用React JS时,
因此,我建议您使用React-Select

  1. 使用“ NPM i- save react-select”添加软件包。
  2. 导入作为组件
  3. 使用< select {data}/>以JSX格式
  4. 将JSON数据添加到{data}。

:反应选择NPM https://reaect-select.com/home

参考文档

As I see you are using React js,
so I will suggest you, to use React-select for better functionality

  1. Add Package using "npm i --save react-select".
  2. Import as a Component
  3. use <Select {data}/> in jsx format
  4. Add json data to {data}.

Reference documantion: React-select npm https://react-select.com/home

Everything is perfectly documented

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文