reactjs - 如何在点击功能上执行以在反应中显示来自搜索栏的过滤结果
问题描述
我正在开发一个组件,用户搜索一个术语并通过过滤器将其返回给他们。我useContext hook
用来通过 db 传递数据axios
。我想使用中的按钮CompSearch component
来呈现结果,而不是让它们显示在击键上。我的问题是如何通过按钮单击呈现结果?
解决方案
请按照以下步骤来实现。
- 将元素更改
input
为不受控制的组件。 - 在 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
如果您需要进一步的支持,请告诉我。