React:用像<span>这样的组件替换字符串,以便用颜色突出显示

问题描述 投票:0回答:1

我目前正在寻找一种解决方案,用一个组件替换较大字符串的一部分以突出显示该部分。

我试过这个:

function highlighted(text) {
    text.replace(highlightedPart, match => {
      return (
        <div>
          <span style={{ color: "red" }}>{match}</span>;
        </div>
      );
    });
  }

但 .replace 似乎不适合它。因为我在字符串中得到了 [Object, Object]。有简单的解决办法吗?

javascript reactjs
1个回答
0
投票

您可以使用

reactStringReplace
来完成此操作。

首先,安装

react-string-replace

Npm:

npm i react-string-replace

纱线:

yarn add react-string-replace

然后在

highlighted
函数中使用它,如下所示:

function highlighted(text) {
    const newText = reactStringReplace(text, highlightedPart, match => {
        return (
            <div>
                <span style={{ color: "red" }}>{match}</span>
            </div>
        );
    });

    return newText
}

然后你可以像这样使用它:

root.render(
    <React.StrictMode>
        {highlighted(text /* Text to be highlighted */)}
    </React.StrictMode>
);
© www.soinside.com 2019 - 2024. All rights reserved.