К счастью, я работал над проектом, в котором я использовал Material UI, поэтому я смог использовать ваш компонент в своей собственной кодовой базе и немного отладить его.
![enter image description here](https://i.stack.imgur.com/cGinh.png)
- Я использую машинопись, поэтому некоторые типы добавляются в твой код, и если ты не знаком с Тайпскриптом, это может показаться немного странным.
- Об обратном процесс, ключ в том, чтобы очистить вещи при изменении вашего шаблона.
- Я использовал внутреннее состояние для целей отладки, которое, конечно, можно заменить его на 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>
);
};