搜尋

首頁  >  問答  >  主體

如何將其轉換為 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])}

而不是在我的組件中使用它工作正常。

P粉248602298P粉248602298562 天前682

全部回覆(1)我來回復

  • P粉211600174

    P粉2116001742023-09-09 13:00:55

    只需建立一個帶有 props 的新元件即可。試試這個...

    1

    2

    export default function HighlightText({text}) {

     return <span className="Add_HighlightText_Class" >{text}</span>

    回覆
    0
  • 取消回覆