【问题标题】:Get the "ID" of the selected value with material-ui autocomplete使用material-ui自动完成获取所选值的“ID”
【发布时间】:2020-10-26 22:56:35
【问题描述】:

我正在使用带有 material-ui 的自动完成组件。

  1. 搜索栏“customerList”中的数据没有问题。但我无法获得我选择的数据的“ID”号。我要获取选中数据的ID号。

  2. 此外,还会出现如下错误。我该如何解决这个问题?

enter image description here

import Autocomplete from '@material-ui/lab/Autocomplete';


class AppointmentFormContainerBasic extends React.PureComponent {
  constructor(props) {
    super(props);
  }

  render() {

    const textEditorProps = (field) => ({
      variant: 'outlined',
      onChange: ({ target: change }) => this.changeAppointment({
        field: [field], changes: change.value
      }),
      value: displayAppointmentData[field] || '',
      className: classes.textField
    });

    const customerList = [
      {id: "1", customerName: 'John', customerSurname: "test0"},
      {id: "2", customerName: 'Bob', customerSurname: "test1"},
      {id: "3", customerNametle: 'steve', customerSurname: "test2"},
      {id: "4", customerName: 'steve', customerSurname: "test3"},
      {id: "4", customerName: 'natalia', customerSurname: "test4"}
    ];

    return (
      <AppointmentForm.Overlay
        visible={visible}
        target={target}
        fullSize
        onHide={onHide}>
        <div>
          <div className={classes.content}>
            <div className={classes.wrapper}>
              <Create className={classes.icon} color="action" />
              <Autocomplete
                id="free-solo-demo"
                freeSolo
                options={customerList.map( (option) => {
                  if (top100Films.customerName === undefined) {
                    console.log("undefined")
                  } else {
                    console.log("option.customerName")
                  }
                  return option.customerName + " " + option.customerSurname;
                })}

                
                defaultValue={displayAppointmentData['customerName']}
                onInputChange={(event, newInputValue) => {
                  this.changeAppointment({
                    field: ['customerName'], changes: newInputValue,
                    value: displayAppointmentData[newInputValue] || '',
                  });
                }}

              />
            </div>

        </div>
      </AppointmentForm.Overlay>
    );
  }
}

【问题讨论】:

  • 运气好吗?我也面临同样的问题。需要获取对象的Id。不是显示值。

标签: javascript reactjs autocomplete material-ui


【解决方案1】:

编辑 从以下示例中可以看出,onChange 方法的 newValue 参数返回一个对象。

import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function ComboBox() {
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={option => option.title}
      style={{ width: 300 }}
      renderInput={params => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
      onChange={(event, newValue) => {
        console.log(JSON.stringify(newValue, null, ' '));
      }}
    />
  );
}

const top100Films = [
  { id: 0, title: "The Shawshank Redemption", year: 1994 },
  { id: 1, title: "The Godfather", year: 1972 },
  { id: 2, title: "The Godfather: Part II", year: 1974 },
  { id: 3, title: "The Dark Knight", year: 2008 },
  { id: 4, title: "12 Angry Men", year: 1957 }
];

不幸的是,您的代码只是一个片段,很难确定为什么它在您的情况下不起作用。

【讨论】:

  • 是的,我可以得到我已经选择的值。但我无法获得我选择的值的 ID 号。我要获取身份证号
  • 用户将看到他们选择的“customerName”字段。在后台;将收到选定的 ID 号。 {id:“1”,customerName:“John”,customerSurname:“test0”},
【解决方案2】:

在使用freeSoloAutocomplete 从对象中进行选择时,我遇到了同样的问题。 onChangeonInputChange 都不返回来自 options 的对象,只返回标签。没有freeSolo 也可以。

我通过我的选项来找到匹配的选项。然后我使用 SourceSelect 将其返回给组件。它不漂亮,但它有效。这是我的代码,它是 TypeScript,但“解决方案”也适用于 JavaScript。

import React, {ChangeEvent} from "react";
import {Autocomplete} from "@material-ui/lab";
import {TextField} from "@material-ui/core";

type SourceSelectParams =
    {
     updateSource:(source:Source)=> void
     sourceOptions:Source[]
     preSelected:Source
    }

export default function SourceSelect(props:SourceSelectParams){

        function optionForLabel(label:string):Source{
            let toReturn = props.sourceOptions.find(
                            (source:Source)=>{ return source.name === label}
)
            if(toReturn){
                return toReturn
            }
            return {name:label}
        }

        function update(event:ChangeEvent<{}>, value:Source|string|null) {
            if(value === null){
                return
            }else if( typeof value === 'string'){
                props.updateSource(optionForLabel(value))
            }else{
                props.updateSource( value)
            }
        }


        return(<Autocomplete  options={props.sourceOptions}
                              value={props.preSelected}
                              getOptionLabel={(option) => option.name}
                              onInputChange={update}
                              onChange={update}
                              renderInput={
                                  (params) => <TextField {...params}
                                                                  label="Source"
                                                                  variant="outlined"

                              />}
                              freeSolo
                              autoSelect
                              id={'source'}/>)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2020-05-04
    • 1970-01-01
    • 2020-02-29
    相关资源
    最近更新 更多