如何將其轉換為 html 元素?
我正在嘗試建立一個突出顯示句子中單字的函數。這是對應的程式碼。
1 2 3 4 5 6 7 8 9 10 11 12 13 | highlightText = () => {
const {
questionItem,
} = this.props;
const words = questionItem.split(/\s+/);
const highlighted = words.map((word, index) => (
<span key={index} className= "highlighted-word" >{word}</span>
));
const text = highlighted.join( ' ' );
console.log(text);
console.log({ highlighted });
return highlighted;
}
|
在這裡,如果我控制台“文字”,我會得到[Object object],所以我會返回“突出顯示”,然後使用reduce加入它。
1 | const text3 = <p>{this.highlightText().reduce((prev, curr) => [prev, ' ' , curr])}</p>;
|
我想在元件中使用這個「text3」。問題是我得到的「text3」為
我希望它是一個 HTML 元素,以便我可以在我的元件中使用它。我該如何轉換它?
另外,如果我直接在網頁中顯示
{this.highlightText().reduce((prev, curr) => [prev, ' ', curr])}
而不是在我的組件中使用它工作正常。