【问题标题】:Material UI Autocomplete implementation with options containing array of objects (ID and label)Material UI 自动完成实现,带有包含对象数组(ID 和标签)的选项
【发布时间】:2019-12-15 13:52:03
【问题描述】:

我正在为我的项目使用 Material UI 自动完成。如official documentation所示,我的选择是,

let options = [
   { id: "507f191e810c19729de860ea", label: "London" },
   { id: "u07f1u1e810c19729de560ty", label: "Singapore" },
   { id: "lo7f19re510c19729de8r090", label: "Dhaka" },
]

然后,我使用Autocomplete作为,

import React, { Component, Fragment, useState } from "react"
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
import options from "/options"

function SelectLocation(props){
    const [ input, setInput ] = useState("");

    const getInput = (event,val) => {
        setInput(val);
    }

    return (
        <Autocomplete
            value={input}
            options={options}
            renderOption={option => <Fragment>{option.label}</Fragment>}}
            getOptionLabel={option => option.label}
            renderInput={params => {
                return (
                    <TextField 
                        {...params} 
                        label={props.label} 
                        variant="outlined" 
                        fullWidth
                    />
                )
            }}
            onInputChange={getInput}
        />
    )
}

现在我的 UI(选项列表)显示了我的预期。 问题是,我将London 或Singapore 作为我的input 的值,但我想从该输入中获取所选对象或ID。

我已经彻底遵循了他们的文档,但找不到方法!

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    onInputChange 使用输入的实际内容触发。

    您可能希望使用input props 公开的onChange 事件,该事件将返回所选元素。然后,该 ID 应在您的 getInput 回调中以 val.id 的形式提供。

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 2020-03-04
      • 2020-03-27
      • 1970-01-01
      • 2021-02-16
      相关资源
      最近更新 更多