reactjs 在React.js上使用突出显示文本< mark>

63lcw9qa  于 2023-02-08  发布在  React
关注(0)|答案(1)|浏览(179)

我正在尝试用React做一个实时的文本高亮显示器,现在这是我到目前为止得到的代码,它的灵感来自于一个使用innerHTML的解决方案,它不起作用。

const Highlighter = () => {
  const [data, setData] = useState("");
  const [search, setSearch] = useState("");
  const getInput = (input) => {
    setData(input.target.value);
  };
  const textoToSearch = (input) => {
    setSearch(input.target.value);
    search.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    let pattern = new RegExp(`${search}`, "gi");
    let teste = data.replace(pattern, (match) => `<mark>${match}</mark>`);
    console.log(teste)
  };

  return (
    <div>
      <textarea data-testid="source-text" onChange={getInput} />
      <input
        className="search"
        data-testid="search-term"
        onChange={textoToSearch}
      />
      <p>
        case sentitive?
        <input type="checkbox" data-testid="case-sensitive" />
      </p>
      <div data-testid="result">{data}</div>
    </div>
  );
};

export default Highlighter;
d5vmydt9

d5vmydt91#

你可以很容易地使用mark.js.install mark.js npm包。
那么下面的代码就可以了。

import React, { useState } from "react";
import "./styles.css";
import Mark from "mark.js";

export default function App() {
  const [searchTerm, setSearchterm] = useState("");
  const markInstance = new Mark(document.querySelector("#search-node"));

  const handleSearch = (event) => {
    setSearchterm(event.target.value);
    markInstance.unmark({
      done: () => {
        markInstance.mark(event.target.value);
      }
    });
  };

  return (
    <div className="App">
      <input
        placeholder="start typing here"
        value={searchTerm}
        onChange={handleSearch}
      />
      <div id="search-node">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
        <p>
          Lorem ipsum dolor sit āmet, consetetur sadipscing elitr, sed diam
          nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
          sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
          rebum. Stet clita kasd gubergren, nò sea takimata sanctus est Lorem
          ipsum dolor sit amet.
        </p>
      </div>
    </div>
  );
}

下面是codesandbox的示例

相关问题