我目前正在寻找一种解决方案,用一个组件替换较大字符串的一部分以突出显示该部分。
我试过这个:
function highlighted(text) {
text.replace(highlightedPart, match => {
return (
<div>
<span style={{ color: "red" }}>{match}</span>;
</div>
);
});
}
但 .replace 似乎不适合它。因为我在字符串中得到了 [Object, Object]。有简单的解决办法吗?
您可以使用
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>
);