简体   繁体   English

使用 material-ui 自动完成获取所选值的“ID”

[英]Get the "ID" of the selected value with material-ui autocomplete

I'm using the autocomplete component with material-ui.我将自动完成组件与 material-ui 一起使用。

  1. The data in "customerList" in the search field is no problem.搜索栏“customerList”中的数据没有问题。 But I can't get the "ID" number of the data I selected.但我无法获得我选择的数据的“ID”号。 I want to get the ID number of the selected data.我想获取所选数据的 ID 号。

  2. Also, an error like below appears.此外,还会出现如下错误。 How can I fix this?我怎样才能解决这个问题?

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>
    );
  }
}

EDIT As you can see from the following sample the newValue param of onChange method returns an object.编辑从以下示例中可以看出,onChange 方法的 newValue 参数返回 object。

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 }
];

在此处输入图像描述 Unfortunately your code is just a fragment and it hard to determine why it does not work in your case.不幸的是,您的代码只是一个片段,很难确定为什么它在您的情况下不起作用。

I had the same issue when selecting from objects using freeSolo with Autocomplete .在使用freeSoloAutocomplete从对象中进行选择时,我遇到了同样的问题。 Neither onChange nor onInputChange returns the object from options , only the label. onChangeonInputChange都不从options返回 object,只返回 label。 Without freeSolo that works.没有freeSolo就可以了。

I resorted to going through my options to find the one that matches.我求助于通过我的选项来找到匹配的选项。 Then I return that to the component using SourceSelect.然后我使用 SourceSelect 将其返回给组件。 It is not pretty, but it works.它不漂亮,但它有效。 This is my code, it is TypeScript, but the "solution" will work for JavaScript as well.这是我的代码,它是 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'}/>)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Material-UI 自动完成中获取选定的值 - Getting selected value in Material-UI Autocomplete 如何获取 material-ui 的自动完成 Select 的值? - How can I get the value of the Autocomplete Select of material-ui? 获取 React material-UI 自动完成中的值 - Getting the value in the React material-UI Autocomplete material-ui DropDown,具有imag的选定值 - material-ui DropDown with imag on selected value React material-ui Autocomplete 的多个选定值? - Multiple selected values of React material-ui Autocomplete? React Material-UI Autocomplete:如何在更改另一个字段中的值时清除在自动完成字段中选择的多个值(mui 芯片)? - React Material-UI Autocomplete: How to clear multiple values (mui chips) selected in a Autocomplete field on changing the value in another field? Material-ui 自动完成不会根据值属性更改其值 - Material-ui autocomplete not changing its value based on value prop ReactJs 从 Material UI 自动完成中获取 id 而不是值 - ReactJs get id instead of value from Material UI Autocomplete 无法使用 select 项目从 material-ui 自动完成和 onchange 获取 event.target.value - Cant get event.target.value using select item from material-ui autocomplete with onchange 以编程方式在 material-ui 自动完成文本字段中设置值 - Programmatically set value in material-ui Autocomplete TextField
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM