ReactJS 中的文本替换

Text replacing in ReactJS

我目前正在编写一些代码来获取文本块中的文本(来自 cms)并替换 CMS 中定义的所谓 'dynamic words',因此当您单击 'dynamic word'它会给你一个警报。我现在有了这段代码,但它不起作用,它确实适用于硬编码文本而不是来自 CMS 的动态词。 谁能看出问题出在哪里?

如需更多信息,请留言(例如,如果您需要了解指定的 console.log 返回的内容 :))

import { useEffect } from 'react';
import { TextBlock } from './ArticleBodyText.styles';

export const ArticleBodyText = ({ item, dynamic_words }) => {
  useEffect(() => {
    const el = document.getElementById('this-text');
    const text = el.innerHTML;
    dynamic_words.map(word => {
      const dynamic_word = word.word?.[0].text;
      const newText = text.replace(
        `/\b${dynamic_word}\b/g`,
        `<span class='dynamic-word'>${dynamic_word}</span>`
      );
      el.innerHTML = newText;
      const spans = el.querySelectorAll('.dynamic-word');
      for (let i = 0; i < spans.length; i += 1) {
        spans[i].addEventListener(
          'click',
          function () {
            if (this.innerHTML === dynamic_word) {
              alert('You clicked a dynamic word!');
            }
          },
          false
        );
      }
    });
  });

  return item?.primary?.body_text.map(bodytext => (
    <TextBlock
      id="this-text"
      key={bodytext.text}
      dangerouslySetInnerHTML={{ __html: bodytext.text }}
    />
  ));
};

编辑: 工作版本:

import { useEffect } from 'react';
import { TextBlock } from './ArticleBodyText.styles';

export const ArticleBodyText = ({ item, dynamic_words }) => {
  useEffect(() => {
    const el = document.getElementById('this-text');
    const text = el.innerHTML;
    const newText = text.replace(/\bte\b/g, "<span class='dynamic-word'>te</span>");
    el.innerHTML = newText;
    const spans = el.querySelectorAll('.dynamic-word');
    for (let i = 0; i < spans.length; i += 1) {
      spans[i].addEventListener(
        'click',
        function () {
          if (this.innerHTML === 'te') {
            alert('Je hebt op een dynamic word geklikt!');
          }
        },
        false
      );
    }
  });

  return item?.primary?.body_text.map(bodytext => (
    <TextBlock
      id="this-text"
      key={bodytext.text}
      dangerouslySetInnerHTML={{ __html: bodytext.text }}
    />
  ));
};

这样你就可以创建动态正则表达式

const word = "something";
const sentence = "This is something";

let first = "\b",
  second = "\b";

const regex = new RegExp(first + word + second, "g");

const newSent = sentence.replace(regex, "Inder");
console.log(newSent);

修复了,我改成:

const dynamic_word = word.word?.[0].text;
      const first = '\b';
      const second = '\b';
      const regex = new RegExp(first + dynamic_word + second, 'g');
      const newText = text.replace(regex, `<span class="dynamic-word">${dynamic_word}</span>`);

replace 需要正则表达式或字符串(精确匹配,而不是看起来像正则表达式的字符串)。您将需要从模板文字创建一个正则表达式:

const oldText = "the sly brown fox is sly"
const dynamic_word = "sly"
const newText = oldText.replaceAll(
  new RegExp(`\b${dynamic_word}\b`, 'g'),
  `<span class='dynamic-word'>${dynamic_word}</span>`
);

console.log(newText)

注:

  • 需要在模板文字中转义 \b 分词标志
  • 您必须使用 g 标志,否则它只会替换第一次出现的