1

最初 string是这样的:-

My first name is @John# and last name is %Smith#.

我将在哪里替换:-

  • @<span className="contentDescHighlighted">
  • %<span className="contentDescHighlighted content_bold">
  • #</span>

工作代码如下: -

  const handleAddingHighlight = (data) => {
    let changeAT = data.replaceAll(`@`, `<span className="contentDescHighlighted">`)
    let changePercentage = changeAT.replaceAll(`%`, `<span className="contentDescHighlighted content_bold">`)
    let highlightedData = changePercentage.replaceAll(`#`, `</span>`); console.log(highlightedData)

    return highlightedData
  }

更改后string,我将使用如下方式注入它们:-dangerouslySetInnerHTML

  <p 
    className="contentDesc" 
    dangerouslySetInnerHTML={{__html: handleAddingHighlight(`My first name is @John# and last name is %Smith#.`)}}
  ></p>

不幸的是,应用的样式/类名根本没有任何效果,如下所示:-

  // what it should looks like
  <p className="contentDesc">
    My first name is <span className="contentDescHighlighted">John</span> and last name is <span className="contentDescHighlighted content_bold">Smith</span>.
  </p>
  // current outcome when using dangerouslySetInnerHTML
  <p 
    className="contentDesc" 
    dangerouslySetInnerHTML={{__html: handleAddingHighlight(`My first name is @John# and last name is %Smith#.`)}}
  ></p>

在此处输入图像描述

完整的组件将如下所示
export default function Test() {
  const handleAddingHighlight = (data) => {
    let changeAT = data.replaceAll(`@`, `<span className="contentDescHighlighted">`)
    let changePercentage = changeAT.replaceAll(`%`, `<span className="contentDescHighlighted content_bold">`)
    let highlightedData = changePercentage.replaceAll(`#`, `</span>`); console.log(highlightedData)

    return highlightedData
  }

  return (
    <>
      {/* what it should looks like */}
      <p className="contentDesc">
        My first name is <span className="contentDescHighlighted">John</span> and last name is <span className="contentDescHighlighted content_bold">Smith</span>.
      </p>
      {/* current outcome when using dangerouslySetInnerHTML */}
      <p 
        className="contentDesc" 
        dangerouslySetInnerHTML={{__html: handleAddingHighlight(`My first name is @John# and last name is %Smith#.`)}}
      ></p>
    </>
  )
}
4

1 回答 1

0

这就是问题所在。使用dangerouslySetInnerHTML属性呈现的内容必须是HTML元素。他们根本不是JSX 。它应该是

class

(这是 HTML 属性)

代替

className

(这是 JSX 属性)

于 2021-11-09T04:36:14.093 回答