如何实现两个搜索词

rbl8hiat  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(474)

如何在react中实现两个搜索词?第一个搜索项是api中的名称,第二个搜索项是元素的孙子的innerhtml(孙子是元素数组)。用户应该能够通过两个搜索词一起或单独过滤搜索。

  1. import React, { useState } from "react";
  2. import Student from "./Student";
  3. import Input from "./Input";
  4. import "../stylesheets/StudentsContainer.scss";
  5. const StudentsContainer = ({ students }) => {
  6. const [searchByName, setSearchByName] = useState("");
  7. const [searchByTag, setSearchByTag] = useState("");
  8. const [tags, setTags] = useState([]);
  9. const addTagClick = (newTag) => {
  10. setTags((prevTags) => [...prevTags, newTag]);
  11. };
  12. const renderStudentsByNameSearch = () => {
  13. return students
  14. .filter((student) => {
  15. if (searchByName.length < 2) {
  16. return student;
  17. } else {
  18. const fullName = student.firstName.concat(student.lastName);
  19. return fullName
  20. .toLowerCase()
  21. .includes(searchByName.toLocaleLowerCase());
  22. }
  23. })
  24. .map((student) => {
  25. return (
  26. <Student
  27. tags={tags}
  28. addTagClick={addTagClick}
  29. key={student.id}
  30. student={student}
  31. />
  32. );
  33. });
  34. };
  35. return (
  36. <section className="students-container">
  37. <Input
  38. value={searchByName}
  39. placeholder="Search by name"
  40. onChange={({ target }) => setSearchByName(target.value)}
  41. />
  42. <Input
  43. placeholder="Search by tag"
  44. onChange={({ target }) => setSearchByTag(target.value)}
  45. />
  46. {renderStudentsByNameSearch()}
  47. </section>
  48. );
  49. };
  50. export default StudentsContainer;

谢谢你的帮助!

7gyucuyw

7gyucuyw1#

我不完全确定你在问什么。如果您只是询问如何使用标记和名称筛选学生数组,并且您已经知道ui部分。你可以这样做。
因为你从来没提过你的 students 数组看起来,我假设如下:

  1. [
  2. {
  3. "firstName": "",
  4. "lastName": "",
  5. "tags": [
  6. "tag1",
  7. "tag2"
  8. ]
  9. }
  10. ]
  1. const [searchByName, setSearchByName] = useState("");
  2. const [searchByTags, setSearchByTags] = useState([]); // I don't think it is a good idea to let people to search by one and only one tag, I changed it multiple tags
  3. const [students, setStudents] = useState([]); // all avalible students
  4. // this is the list of student you should display in the search result
  5. const filteredStudents = useMemo(() => students.filter(({ firstName, lastName, tags}) =>
  6. searchByName === "" || (firstName + " " + lastName).includes(searchByName) // include this student if the search string is empty or the full name includes the search string
  7. && tags.length === 0 || searchByTags.every(tag => tags.includes(tag)) // and if the search tags are empty or student matches all the search tags
  8. ), [students, searchByName, searchByTags]);
展开查看全部

相关问题