使object value加粗中的某些字符或字母发生反应



假设我有一个对象数组:

const options = [
{
text: "this is the text",
description: "The word 'test' should be bold"
},
{
text: "this is the text",
description: "The word 'another-word' should be bold"
}
]

组件呈现如下内容:

return (
{
options.map(option => {
<p className="text-green-500">{option.description}</p>
})
}
)

现在我必须让单词/s "test"one_answers";another-word"大胆的分别。在某些情况下,它只能是一个单词内的字符。

我通过替换description的值来回答它。而不是:

description: "this is the text"

我也改了:

description: <div>this is the <strong>text></strong></div>

您可以创建一个函数,将''中的字符串替换为<b>包装器。

const highlight = (text) => text.replace(/'([^']+)'/g, "<b>$1</b>")

然后这样设置innerHTML:

return options.map(({ description }) => 
<p dangerouslySetInnerHTML={{ __html: highlight(description) }}></p>
)

如果这些字符串是用户输入,则需要在执行此操作之前对字符串进行消毒。

const highlight = (text) => text.replace(/'([^']+)'/g, "<b>$1</b>")
function App() {
const options = [{
text: "this is the text",
description: "The word 'test' should be bold"
},
{
text: "this is the text",
description: "The word 'another-word' should be bold"
}
]

return options.map(({ description }) => 
<p dangerouslySetInnerHTML={{ __html: highlight(description) }}></p>
)
};

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>


你可以完全避免innerHTML路由。在这种情况下,您需要将每个字符串分割成片段,然后呈现它们。

const highlight = (text) =>
Array.from(text.matchAll(/([^']*)'*([^']*)'*([^']*)/g), ([m, p1, p2, p3]) =>
m ? (
<>
{p1}
<b>{p2}</b>
{p3}
</>
) : null
);

然后像这样渲染:

return options.map(({ description }) => 
<p>{highlight(description)}</p>
)

这可能是最简单的方法,只需从处理保存文本部分的函数返回一块JSX。

Stackblitz运行代码:https://stackblitz.com/edit/react-ts-gewz6v?file=App.tsx,index.tsx

const options = [
{
text: 'this is the text',
description: "The word 'test' should be bold",
},
{
text: 'this is the text',
description: "The word 'another-word' should be bold",
},
];
const boldText = (text) => {
const termToBold = text.match(/'([^']+)'/)[1];
const startIndex = text.toLowerCase().indexOf("'");
return (
<React.Fragment>
{text.slice(0, startIndex)}
<strong>
{text.slice(startIndex, startIndex + 2 + termToBold.length)}
</strong>
{text.slice(startIndex + 2 + termToBold.length)}
</React.Fragment>
);
};
return (
<div>
{' '}
{options.map((option) => {
return <p className="text-green-500">{boldText(option.description)}</p>;
})}
</div>
);

相关内容

最新更新