如何实现两个搜索词

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

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

import React, { useState } from "react";
import Student from "./Student";
import Input from "./Input";

import "../stylesheets/StudentsContainer.scss";

const StudentsContainer = ({ students }) => {
  const [searchByName, setSearchByName] = useState("");
  const [searchByTag, setSearchByTag] = useState("");
  const [tags, setTags] = useState([]);

  const addTagClick = (newTag) => {
    setTags((prevTags) => [...prevTags, newTag]);
  };

  const renderStudentsByNameSearch = () => {
    return students
      .filter((student) => {
        if (searchByName.length < 2) {
          return student;
        } else {
          const fullName = student.firstName.concat(student.lastName);
          return fullName
            .toLowerCase()
            .includes(searchByName.toLocaleLowerCase());
        }
      })
      .map((student) => {
        return (
          <Student
            tags={tags}
            addTagClick={addTagClick}
            key={student.id}
            student={student}
          />
        );
      });
  };

  return (
    <section className="students-container">
      <Input
        value={searchByName}
        placeholder="Search by name"
        onChange={({ target }) => setSearchByName(target.value)}
      />
      <Input
        placeholder="Search by tag"
        onChange={({ target }) => setSearchByTag(target.value)}
      />
      {renderStudentsByNameSearch()}
    </section>
  );
};

export default StudentsContainer;

谢谢你的帮助!

7gyucuyw

7gyucuyw1#

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

[
  {
    "firstName": "",
    "lastName": "",
    "tags": [
      "tag1",
      "tag2"
    ]
  }
]
const [searchByName, setSearchByName] = useState("");
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
const [students, setStudents] = useState([]); // all avalible students

// this is the list of student you should display in the search result
const filteredStudents = useMemo(() => students.filter(({ firstName, lastName, tags}) =>
  searchByName === "" || (firstName + " " + lastName).includes(searchByName) // include this student if the search string is empty or the full name includes the search string 
  && tags.length === 0 || searchByTags.every(tag => tags.includes(tag)) // and  if the search tags are empty or student matches all the search tags
), [students, searchByName, searchByTags]);

相关问题