Как создать компонент фильтра, например Google chrome find (Cntrl + F), который распознает текст и меняет его цвет фона - PullRequest
0 голосов
/ 24 марта 2020

world, в прошлый день я хотел создать компонент поиска / фильтра, который будет вести себя как Google chrome найти компонент, как показано ниже:

enter image description here

Но проблемы:

  1. Я могу найти слово и заменить его на <span class="text-found">${CHOOSEN_WORD}</span>, но только первые три буквы
  2. Я не могу перевернуть его (удалить стиль из букв )

Это мои последние усилия:

у меня есть компонент с именем Content, как и у него:

import React, { useEffect } from "react";
import { Typography } from "@material-ui/core";

const Content = ({ pattern }) => {
  useEffect(() => {
    searchText(pattern);
  }, [pattern]);


  const searchText = pattern => {
    let list = document.querySelectorAll(".text-row");

    for (let i = 0; i < list.length; i++) {
        let res = list[i].innerHTML.replace(
          new RegExp(pattern, "g"),
          `<span class="text-found">${pattern}</span>`
        );
        document.querySelectorAll(".text-row")[i].innerHTML = res;
    }
  };

  return (
    <div>
      <Typography className="text-row">
        Lorem Ipsum is simply dummy text of the printing and typesetting
        industry. Lorem Ipsum has been the industry's standard dummy text ever
        since the 1500s, when an unknown printer took a galley of type and
        scrambled it to make a type specimen book. It has survived not only five
        centuries, but also the leap into electronic typesetting, remaining
        essentially unchanged. It was popularised in the 1960s with the release
        of Letraset sheets containing Lorem Ipsum passages, and more recently
        with desktop publishing software like Aldus PageMaker including versions
        of Lorem Ipsum.
      </Typography>
      <Typography className="text-row">
        Lorem Ipsum is simply dummy text of the printing and typesetting
        industry. Lorem Ipsum has been the industry's standard dummy text ever
        since the 1500s, when an unknown printer took a galley of type and
        scrambled it to make a type specimen book. It has survived not only five
        centuries, but also the leap into electronic typesetting, remaining
        essentially unchanged. It was popularised in the 1960s with the release
        of Letraset sheets containing Lorem Ipsum passages, and more recently
        with desktop publishing software like Aldus PageMaker including versions
        of Lorem Ipsum.
      </Typography>
    </div>
  );
};

export default Content;

, и это мой результат:

enter image description here

1 Ответ

2 голосов
/ 24 марта 2020

К счастью, я работал над проектом, в котором я использовал Material UI, поэтому я смог использовать ваш компонент в своей собственной кодовой базе и немного отладить его.

enter image description here

  • Я использую машинопись, поэтому некоторые типы добавляются в твой код, и если ты не знаком с Тайпскриптом, это может показаться немного странным.
  • Об обратном процесс, ключ в том, чтобы очистить вещи при изменении вашего шаблона.
  • Я использовал внутреннее состояние для целей отладки, которое, конечно, можно заменить его на React props.

A Переписанная версия вашего компонента, которая просто работает:

const Test = () => {
  const [pattern, setPattern] = useState<string>("");
  useEffect(() => {
    let list = document.querySelectorAll(".text-row");
    const searchText = (pattern: string) => {
      if (!pattern) return;
      for (let i = 0; i < list.length; i++) {
        let res = list[i].innerHTML.replace(
          new RegExp(pattern, "g"),
          `<span class="text-found">${pattern}</span>`
        );
        document.querySelectorAll(".text-row")[i].innerHTML = res;
      }
    };
    searchText(pattern);
    const cleanUp = () => {
      for (let i = 0; i < list.length; i++) {
        let res = list[i].innerHTML
          .replace(new RegExp('<span class="text-found">', "g"), "")
          .replace(new RegExp("</span>", "g"), "");
        document.querySelectorAll(".text-row")[i].innerHTML = res;
      }
    };
    return cleanUp;
  }, [pattern]);

  return (
    <div>
      <input onChange={e => setPattern(e.target.value)} />
      <Typography className="text-row">
        Lorem Ipsum is simply dummy text of the printing and typesetting
        industry. Lorem Ipsum has been the industry's standard dummy text ever
        since the 1500s, when an unknown printer took a galley of type and
        scrambled it to make a type specimen book. It has survived not only five
        centuries, but also the leap into electronic typesetting, remaining
        essentially unchanged. It was popularised in the 1960s with the release
        of Letraset sheets containing Lorem Ipsum passages, and more recently
        with desktop publishing software like Aldus PageMaker including versions
        of Lorem Ipsum.
      </Typography>
      <Typography className="text-row">
        Lorem Ipsum is simply dummy text of the printing and typesetting
        industry. Lorem Ipsum has been the industry's standard dummy text ever
        since the 1500s, when an unknown printer took a galley of type and
        scrambled it to make a type specimen book. It has survived not only five
        centuries, but also the leap into electronic typesetting, remaining
        essentially unchanged. It was popularised in the 1960s with the release
        of Letraset sheets containing Lorem Ipsum passages, and more recently
        with desktop publishing software like Aldus PageMaker including versions
        of Lorem Ipsum.
      </Typography>
    </div>
  );
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...