MUI AutoComplete 选择的值返回相关对象。

huangapple go评论127阅读模式
英文:

MUI AutoComplete selected value to return the related object

问题

我已经使用 MUI (v4) 的 Select 组件实现了一个列表。现在我有一个新的功能请求,希望这个列表可以进行搜索,因为它非常长。

似乎在 MUI 库中,我唯一的选项是使用 AutoComplete 组件。

第一个问题 - 是否有使用 Select 组件实现这个功能的选项?

我试图使用 AutoComplete 来实现,但在某一点上不确定如何继续。在 Select 组件中,当从列表中选择一个项目时,我还会得到该值的对象,但 AutoComplete 组件只返回所选的简单字符串值。我找不到获取与之相关的对象的方法。

所以我的第二个问题 - 这是否有意义?如何获取与所选值相关的整个对象,就像在 Select 组件中一样。

我的实现示例:

options = [
  { id: "value1", optionName: "aaa", moreData2: "bbb" },
  { id: "value2", optionName: "ccc", moreData2: "ddd" }
]

使用 Select:

<Select
  id={"options"}
  name={"options"}
  value={JSON.stringify(chosenOption) || ""}
  onChange={onSelect}
>
  <MenuItem key={"options_empty"} value={""}>
    None
  </MenuItem>
  {options.map((option: OptionDto) => (
    <MenuItem key={option.id} id={option.optionName} value={JSON.stringify(option)}>
      {option.optionName}
    </MenuItem>
  ))}
</Select>


使用 AutoComplete:

<Autocomplete
  id={"options"}
  renderInput={(params: any) => <TextField {...params} />}
  options={options}
  getOptionLabel={(option: OptionDto) => option.optionName!}
  onChange={onSelectOption}
/>

请注意,这些是原文中的代码和问题,我已经翻译了它们。

英文:

I have implemented a list with MUI (v4) Select component.
Now I have a new feature request, that this list will be searchable, since it's a very long list.

Seems like my options inside MUI lib is only AutoComplete component.

first question - is there an option to do that with the Select component?

I'm trying to create implementation with AutoComplete, but reaching a spot where I'm not sure how to proceed.
While in Select component, when selecting an item from the list, I also get the object that the value came from,
AutoComplete component only return the flat value selected, meaning the simple string. I can't find a way to get the object related to it.

So my second qurestion - Does this makes sense? How do I get the whole object related to the value selected, same as in Select component.

example of my implementation:

options = [
{ id:&quot;value1&quot;, optionName: &quot;aaa&quot;, moreData2: &quot;bbb&quot; }
{ id: &quot;value2&quot;, optionName: &quot;ccc&quot;, moreData2: &quot;ddd&quot; }
]

With Select:

&lt;Select
                id={&quot;options&quot;}
                name={&quot;options&quot;}
                value={JSON.stringify(chosenOption) || &quot;&quot;}
                onChange={onSelect}
            &gt;
                &lt;MenuItem key={&quot;options_empty&quot;} value={&quot;&quot;}&gt;
                    None
                &lt;/MenuItem&gt;
                {options.map((option: OptionDto) =&gt; (
                    &lt;MenuItem key={option.id} id={option.optionName} value={JSON.stringify(option)}&gt;
                        {option.optionName}
                    &lt;/MenuItem&gt;
                ))}
            &lt;/Select&gt;


With AutoComplete:

&lt;Autocomplete
                id={&quot;options&quot;}
                renderInput={(params: any) =&gt; &lt;TextField {...params} /&gt;}
                options={options}
                getOptionLabel={(option: OptionDto) =&gt; option.optionName!}
                onChange={onSelectOption}
            /&gt;

答案1

得分: 0

你可以使用Autocomplete组件来实现这个功能。你可以传递一个包含label属性和其他你想要的属性的对象数组,然后可以通过onChange来保存所选的值到状态中,包括所有属性。

默认情况下,可见的值是label,但你可以通过添加以下属性来更改它:

getOptionLabel={(option) => option.code}

我为你提供了一个完整的示例代码:

import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

const options = [{ label: 'Option 1', code: "bb" }, { label: 'Option 2', code: "aa" }];

export default function ControllableStates() {
  const [value, setValue] = React.useState<any | null>(options[0]);

  return (
    <div>
      <div>{`value: ${value !== null ? `'${JSON.stringify(value)}'` : 'null'}`}</div>
      <br />
      <Autocomplete
        value={value}
        onChange={(event: any, newValue: string | null) => {
          setValue(newValue);
        }}
        id="demo"
        options={options}
        sx={{ width: 300 }}
        renderInput={(params) => <TextField {...params} label="demo" />}
      />
    </div>
  );
}

请注意,上述代码示例是使用React和Material-UI库创建的。如果你有任何进一步的问题或需要帮助,请告诉我。

英文:

You can use component Autocomplete for doing this.
You can pass an array of object that contain a label attribute an whatever you want, and you can save the value selected ( thanks onChange ) into state, with all attribute.
Default value visible is label, but you can change it with add this attribute:

getOptionLabel=	{(option) =&gt; option.code}

I post for you an example complete:

import * as React from &#39;react&#39;;
import TextField from &#39;@mui/material/TextField&#39;;
import Autocomplete from &#39;@mui/material/Autocomplete&#39;;

const options = [{label:&#39;Option 1&#39;, code:&quot;bb&quot;}, {label:&#39;Option 2&#39;, code:&quot;aa&quot;}];

export default function ControllableStates() {
  const [value, setValue] = React.useState&lt;any| null&gt;(options[0]);

  return (
    &lt;div&gt;
      &lt;div&gt;{`value: ${value !== null ? `&#39;${JSON.stringify(value)}&#39;` : &#39;null&#39;}`}&lt;/div&gt;
      &lt;br /&gt;
      &lt;Autocomplete
        value={value}
        onChange={(event: any, newValue: string | null) =&gt; {
          setValue(newValue);
        }}
        id=&quot;demo&quot;
        options={options}
        sx={{ width: 300 }}
        renderInput={(params) =&gt; &lt;TextField {...params} label=&quot;demo&quot; /&gt;}
      /&gt;
    &lt;/div&gt;
  );
}

答案2

得分: 0

你可以使用 Autocomplete 组件,并且它会传递这个数值。

假设你有一个国家列表,像这样:

countries=[
    {id:1, name:'United States', iso3: 'USA'}
    {id:2, name:'France', iso3: 'FRA'}
    {id:3, name:'Germany', iso3: 'DEU'}
]

现在,你可以像这样获取所选选项的 value

const handleCountryChange = (event, value) => {
    console.log(value); // 输出 {id:1, name:'United States', iso3: 'USA'}
}
英文:

You can use Autocomplete component and it passes the value.

let's say you have a list of countries like this:

countries=[
    {id:1, name:&#39;United States&#39; iso3: &#39;USA&#39;}
    {id:2, name:&#39;France&#39;        iso3: &#39;FRA&#39;}
    {id:3, name:&#39;Germany&#39;       iso3: &#39;DEU&#39;}
]
&lt;Autocomplete
  disablePortal
  size=&quot;small&quot;
  name=&quot;country&quot;
  id=&quot;country&quot;
  options={countries}
  onChange={handleCountryChange}
  renderOption={(props, option) =&gt; ( 
    &lt;Box
      component={&quot;li&quot;}
      {...props}
    &gt;
      {option.label}
    &lt;/Box&gt;
    )}
    renderInput={(params) =&gt; (
      &lt;TextField
          {...params}
          label=&quot;Country&quot;
          autoComplete=&quot;new-password&quot;
      /&gt;
  )}
/&gt;

now you can get the value of the selected option like this.

const handleCountryChange = (event, value) =&gt; {
    console.log(value); // output {id:1, name:&#39;United States&#39; iso3: &#39;USA&#39;} 

huangapple
  • 本文由 发表于 2023年3月7日 22:36:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663342.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定