【问题标题】:Material UI Autocomplete custom renderInputMaterial UI 自动完成自定义 renderInput
【发布时间】:2020-09-18 10:38:15
【问题描述】:

我正在关注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>
    );
  };

如何在&lt;Autocomplete /&gt; 上使用&lt;input /&gt; 组件作为renderInput 属性?

【问题讨论】:

    标签: reactjs autocomplete material-ui


    【解决方案1】:

    更新

    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 被放置在包装&lt;input&gt; 的div 上,因此大多数这些道具不适合像您一样直接放在&lt;input&gt; 元素上。在文档示例的上述代码中,您可以看到它只使用了params.InputProps 中的一件事,即ref。对于选项列表框,此参考是 used for controlling the anchor element。引用也是placed on the &lt;input&gt; itself,但ref 用于非常不同的目的。使用您的代码,只有其中一个引用被使用。

    下面是一个使用&lt;input&gt; 而不是TextField 的工作示例(基于Combo Box example,因为您的沙盒有很多其他与此问题没有直接关系的自定义设置):

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

    【讨论】:

    • 你救了我的一天,先生
    猜你喜欢
    • 2020-11-27
    • 2021-10-04
    • 2020-03-27
    • 2016-10-11
    • 2023-03-24
    • 2021-10-09
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多