reactjs 中的数组搜索和过滤

问题描述 投票:0回答:1

我正在尝试根据用户搜索显示图标

示例 "computer" 是实际的图标名称 ["laptop", "tablet", "device" ] 这些是计算机图标名称的标签

我们必须根据这些标签名称的搜索来显示相应/匹配的图标

icons = [{
         "computer" : ["laptop", "tablet", "device" ],
          "mobile" : ["laptop", "tablet", "device" ] ,
          "arrow" : ["left-arrow",  "right-arrow" ] ,
          "left-arrow" : ["arrow",  "right-arrow" ] ,
          "right-arrow" : ["arrow",  "left-arrow" ] ,
          "car" : [ "maruti", "hundai", "road" ],
          "bus" : [ "road" ]
        }]
   const [usersearch, setUsersearch] = ("computer");

==========

<input defaultValue={usersearch} onChange={(e) => setUsersearch(e.target.value)}  />
    icons.map((ico, index) => {
                    return (
                        <div key={index} >
                            <IcoComponent icon={usersearch} /> 
                        </div>
                    )
                })}
javascript reactjs search frontend
1个回答
0
投票
    export default function App() {
  const icons = {
    computer: ["laptop", "tablet", "device"],
    mobile: ["laptop", "tablet", "device"],
    arrow: ["left-arrow", "right-arrow"],
    "left-arrow": ["arrow", "right-arrow"],
    "right-arrow": ["arrow", "left-arrow"],
    car: ["maruti", "hundai", "road"],
    bus: ["road"],
  };
  const [usersearch, setUsersearch] = useState("");
  return (
    <div>
      <input
        defaultValue={usersearch}
        onChange={(e) => setUsersearch(e.target.value)}
      />

      {icons[usersearch] && icons[usersearch].length
        ? icons[usersearch].map((x, index) => (
            <div key={index}>
              <IcoComponent icon={x} />
            </div>
          ))
        : ""}
    </div>
  );
}

所以这里需要将图标结构从数组重构为对象,以便通过键进行搜索。用户继续输入,如果任何键与图标匹配,则会显示值数组中的以下元素,您可以使用图标

© www.soinside.com 2019 - 2024. All rights reserved.