我最初 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>
</>
)
}