【问题标题】:Render value for no matches found in react-autocomplete在 react-autocomplete 中找不到匹配项的渲染值
【发布时间】:2022-10-16 01:48:17
【问题描述】:

我正在使用 react-autocomplete npm 包在我的 Reactjs 应用程序中构建自动完成功能。到目前为止,我已经能够呈现与用户输入匹配的下拉项,正如您在此包的文档中看到的那样。但是,每当用户的输入与任何下拉项目都不匹配时,我想在下拉列表中生成一个默认文本为No results found。老实说,我真的很挣扎。

我尝试将自定义函数添加到 shouldItemRender 以相应地更改状态和下拉项,但它也无济于事。这是我的代码的 sn-p -


const suggestions=  [{id: 100 , text:  "Aluminium extracts" }, {id: 101 , text:  "Copper extracts" }] 

<Autocomplete
    getItemValue={(item) => item.text}
    items={ suggestions }
    renderItem={(item, isHighlighted) => {
            return <div> {item.text} </div>)
        }
    }
    shouldItemRender={(item, value) => item.text.toLowerCase().indexOf(value.toLowerCase()) > -1}
    // shouldItemRender={(item, value) => handleRender(item, value) }
    value={value}
    onChange={(e, newValue) => { setValue(e.target.value) }}
    onSelect={(v) => handleInput(v)}
    inputProps={{ placeholder: "start typing"}}
/>

如果您能帮助我完成此任务,我将不胜感激。谢谢你。

【问题讨论】:

  • 这有帮助吗? Custom Menu Example
  • 我尝试使用renderMenuitems 进行条件渲染,如上面的示例所示,但它没有帮助,它破坏了一切:(
  • 您能否创建一个最小的可重现 stackblitz 链接?

标签: javascript reactjs react-autocomplete


【解决方案1】:

在没有选项的情况下提供消息的最佳方法是使用renderMenu 道具在没有找到匹配搜索条件的项目时覆盖下拉内容的结果。

import { useState } from "react";

const suggestions = [
  { id: 100, text: "Aluminium extracts" },
  { id: 101, text: "Copper extracts" }
];

export default function App() {
  const [searchTerm, setSearchTerm] = useState("");
  const items = suggestions.filter((item) =>
    item.text.toLowerCase().includes(searchTerm.toLowerCase())
  );
  return (
    <div className="App">
      <Autocomplete
        getItemValue={(item) => item.text}
        renderMenu={(items) =>
          items.length > 0 ? <div children={items} /> : <div>No results found</div>
        }
        items={items}
        renderItem={(item, isHighlighted) => {
          return <div> {item.text} </div>;
        }}
        value={searchTerm}
        onChange={(e, newValue) => {
          setSearchTerm(e.target.value);
        }}
        onSelect={(text) => setSearchTerm(text)}
        inputProps={{ placeholder: "start typing" }}
      />
    </div>
  );
}

【讨论】:

    【解决方案2】:

    你试过这个吗?

    items={ suggestions.lenght ? suggestions : [{id: -1, text: "No results found" }] }
    isItemSelectable=(item)=>item.id !== -1
    

    【讨论】:

    • 不幸的是,它不起作用。
    猜你喜欢
    • 2021-08-21
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多