在我的
React-Bootstrap-Typeahead
中,我需要立即在输入中设置状态变量和 clear 以允许新的搜索。现在发生的事情是:
handleChange
正确执行我需要设置 var
clickedSelection
并重置新搜索的输入。一切都应该被清理并关闭。 (注:我使用的是 AsyncTypeahead
的 React-Bootstrap-Typeahead
变体。)
const [isLoading, setIsLoading] = useState(false);
const [searchResults, setSearchResults] = useState([]);
const [clickedSelection, setClickedSelection] = useState({});
// Fetch Function
const fetchResults = async (token) => {
setIsLoading(true);
const response = await axios.get('/myurl/search/' + token); // Axios for Data Fetch
setSearchResults(response.data); // Set results state var
}
// Handle onChange Function: set 'clickedSelection'
const handleChange = (options) => {
console.log(JSON.stringify(options[0]);
setClickedSelection(options[0]);
}
<AsyncTypeahead
isLoading={isLoading}
onSearch={(query) => {
fetchResults(query)
}}
option={searchResults}
labelKey={option => `${option.firstName ${option.lastName}`}
onChange={handleChange}
/>
经过几个小时的搜索,我终于在文档中发现公共方法 hideMenu 可以满足我的要求。这里是使用 ref 和 typescript 方式。 `
import { Button, Col, Label, Row } from "reactstrap";
import { MenuItem, Typeahead, TypeaheadRef } from "react-bootstrap-typeahead";
import { AddTag } from "@/Constant/constant";
import SVG from "@/CommonComponent/SVG/Svg";
import { useRef, useState } from "react";
import { Option } from "react-bootstrap-typeahead/types/types";
interface DropDownComponentProps {
title: string;
labelKey: string;
placeHolder: string | undefined;
options: { name: string; header: boolean | null; key: string }[];
multiple: boolean | undefined;
isRequired: boolean | undefined;
onChange: Function;
}
const DropDownComponent: React.FC<DropDownComponentProps> = ({
title,
labelKey,
options,
multiple,
isRequired,
placeHolder,
onChange,
}) => {
const typeaheadRef = useRef<TypeaheadRef>(null);
const [selected, setSelected] = useState<Option[]>();
const handleBlur = () => {
typeaheadRef.current?.hideMenu();
};
return (
<Col sm="6">
<Row className="g-2 product-tag">
<Col xs="12">
<Label className="d-block m-0" for="validationServer01" check>
{title}
{isRequired && <span className="txt-danger"> *</span>}
</Label>
</Col>
<Col xs="12">
<i
className="fa fa-angle-down"
style={{
textAlign: "center",
width: "12px",
lineHeight: "10px",
zIndex: 1,
position: "absolute",
top: "50%",
right: "2%",
}}
></i>
<Typeahead
id="multiple-typeahead"
labelKey={labelKey}
multiple={multiple}
options={options}
onChange={(selected) => {
console.log({ selected });
setSelected(selected);
// typeaheadRef.current?.clear();
}}
allowNew={true}
ref={typeaheadRef}
selected={selected}
onBlur={handleBlur}
/>
{placeHolder && <p className="f-light">{placeHolder}</p>}
</Col>
</Row>
</Col>
);
};
export default DropDownComponent;
`