Material UI 自动完成自定义 renderInput

Material UI Autocomplete custom renderInput

我正在按照 https://material-ui.com/components/autocomplete/ 中的各种示例来创建自定义自动完成功能。我正在尝试使用 renderInput 属性 来使用自定义输入组件。我找到的所有示例都使用 TextField 组件,但我想使用常规 input 组件。

问题是,选项永远不会显示。我在这里创建了一个演示(交换 renderInputrenderInputWORKING 以查看工作版本):

https://codesandbox.io/s/epic-johnson-oxy7b?file=/src/App.tsx

renderInput中使用以下代码:

 const renderInput = (params: AutocompleteRenderInputParams) => {
    console.log(params);
    const { InputLabelProps, inputProps, InputProps } = params;
    return (
      <div>
        <label {...InputLabelProps}>foo</label>
        <input {...InputProps} {...inputProps} />
      </div>
    );
  };

如何在 <Autocomplete /> 上为 renderInput 道具使用 <input /> 组件?

更新

Material-UI 的 4.10.1 版本(2020 年 6 月 1 日)在文档中针对此确切案例包含了一个新示例:https://material-ui.com/components/autocomplete/#custom-input.

拉取请求:https://github.com/mui-org/material-ui/pull/21257


文档中最有用的示例是 Customized Autocomplete example,它使用 InputBase 而不是 TextField。此示例包含 renderInput 的以下代码:

         renderInput={(params) => (
            <InputBase
              ref={params.InputProps.ref}
              inputProps={params.inputProps}
              autoFocus
              className={classes.inputBase}
            />
          )}

传递给TextFieldInputProps被放置在包裹<input>的div上,所以这些道具大部分不适合直接放在<input>元素和你一样。在上面文档示例的代码中,您可以看到它只使用了 params.InputProps 中的一个东西,即 ref。这个 ref 是 used for controlling the anchor element for the listbox of options. A ref is also placed on the <input> itself,但是 ref 用于非常不同的目的。使用您的代码,只有一个引用被使用。

下面是一个使用 <input> 而不是 TextField:

import React from "react";
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 => (
        <div ref={params.InputProps.ref}>
          <label {...params.InputLabelProps}>My Label </label>
          <input {...params.inputProps} autoFocus />
        </div>
      )}
    />
  );
}