英文:
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:"value1", optionName: "aaa", moreData2: "bbb" }
{ id: "value2", optionName: "ccc", moreData2: "ddd" }
]
With 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>
With AutoComplete:
<Autocomplete
                id={"options"}
                renderInput={(params: any) => <TextField {...params} />}
                options={options}
                getOptionLabel={(option: OptionDto) => option.optionName!}
                onChange={onSelectOption}
            />
答案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) => option.code}
I post for you an example complete:
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>
  );
}
答案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:'United States' iso3: 'USA'}
    {id:2, name:'France'        iso3: 'FRA'}
    {id:3, name:'Germany'       iso3: 'DEU'}
]
<Autocomplete
  disablePortal
  size="small"
  name="country"
  id="country"
  options={countries}
  onChange={handleCountryChange}
  renderOption={(props, option) => ( 
    <Box
      component={"li"}
      {...props}
    >
      {option.label}
    </Box>
    )}
    renderInput={(params) => (
      <TextField
          {...params}
          label="Country"
          autoComplete="new-password"
      />
  )}
/>
now you can get the value of the selected option like this.
const handleCountryChange = (event, value) => {
    console.log(value); // output {id:1, name:'United States' iso3: 'USA'} 
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论