如何执行点击功能以在反应中显示来自搜索栏的过滤结果

how to execute on click function to show filtered results from search bar in react

我正在开发一个组件,用户可以在其中搜索术语并通过过滤器将其返回给他们。我正在使用 useContext hook 通过 axios 从数据库传递数据。我想使用 CompSearch component 中的按钮来呈现结果,而不是让它们显示在击键上。我的问题是如何通过单击按钮呈现结果?

Here is the code

按照这些步骤来实现。

  1. input 元素更改为不受控制的组件。
  2. 在 React 中使用引用获取值。
import React, { useContext, useRef, useState } from "react";
import CompanyInfoList from "./CompanyInfoList";
import { CompListContext } from "./CompListContext";

const CompSerach = () => {
  const [company, setCompany] = useContext(CompListContext);
  const [searchField, setSearchField] = useState("");
  const [searchShow, setSearchShow] = useState(false);

  const filtered = company.filter((res) => {
    return res.company.toLowerCase().includes(searchField.toLowerCase());
  });

  const inputRef = useRef(null); // 1. Create the ref

  const handleClick = () => {
    const val = inputRef.current.value; // 3. Get the value
    setSearchField(val);

    if (val === "") {
      setSearchShow(false);
    } else {
      setSearchShow(true);
    }
  };

  const searchList = () => {
    if (searchShow) {
      return <CompanyInfoList filtered={filtered} />;
    }
  };

  return (
    <>
      <div>
        <em>
          NOTE: if you search "ABC" or "EFGH" you will see results - my goal is
          to see those results after clicking button
        </em>
        <br />
        <input
          type="search"
          placeholder="search Company Title"
          ref={inputRef} {/* 2. Assign the ref to the Input */}
        />
        <button onClick={handleClick}>Enter</button>
      </div>
      {searchList()}
    </>
  );
};

export default CompSerach;

https://codesandbox.io/s/show-on-button-click-68157003-rot6o?file=/src/TestTwo/CompSearch.js

如果您需要进一步的支持,请告诉我。

const handleChange = (e) => {
    setSearchField(e.target.value);
    if (e.target.value === "") {
      setSearchShow(false);
    } else {
      setSearchShow(true);
    }
    **setCompany(e.target.value);**
  };

我认为你的问题与自动完成类似。