使用React.js和Elasticsearch实现。首先使用React.js创建搜索框组件,然后集成Elasticsearch查询功能实现即时搜索功能。代码示例如下:
import React, { useState, useEffect } from 'react';
import { Client } from '@elastic/elasticsearch';
const client = new Client({
node: 'http://localhost:9200',
});
function SearchBar() {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
useEffect(() => {
async function getResults() {
const { body } = await client.search({
index: 'contacts',
body: {
query: {
match: {
name: query,
},
},
},
});
setResults(body.hits.hits);
}
getResults();
}, [query]);
function handleChange(event) {
setQuery(event.target.value);
}
return (
{results.map(result => (
- {result._source.name}
))}
);
}
export default SearchBar;
上一篇:A"sendto"searchbarliketheoneusedbyGmail
下一篇:A'using'statementgetsmovedautomaticallyoutsideofthenamespace