javascript - 加粗文本中的特定单词 - React Native?
问题描述
我需要替换 boldTextbased on the index value
的地方,{index}
那个词应该是粗体。
例子:
{
sentence: {0} and {1} are great
boldText: ['You', 'Your Family']
}
输出:
你和你的家人都很棒。
解决方案
这是一个简单的例子。
希望对您有所帮助!
const sample = {
sentence: '{0} and {1} are great',
boldText: ['You', 'Your Family']
};
const applyBoldStyle = text => text.sentence.replace(/\{(\d+)\}/g, (match, i) => `<b>${text.boldText[i]}</b>`);
console.log(applyBoldStyle(sample));
请注意,你可以传递任何你想适合 react-native 的东西。这里我传递带有<b>
标签的简单 HTML,这里重要的是replace
函数。让它返回你想要的任何东西。
使用 react-native,您可能希望使用以下内容:
const sample = {
sentence: '{0} and {1} are great',
boldText: ['You', 'Your Family']
};
const applyBoldStyle = text => {
let numberOfItemsAdded = 0;
const result = text.sentence.split(/\{\d+\}/);
text.boldText.forEach((boldText, i) => result.splice(++numberOfItemsAdded + i, 0, <Text style={{fontWeight: 'bold'}}>{boldText}</Text>););
return <Text>{result}</Text>;
};
推荐阅读
- kotlin - 如何在 Intellij 中配置 Kotlin SDK 外部文档?
- visual-studio - 如何创建 .NET Core 2 MVC 解决方案?
- c# - .NET Core 3.1 无法从 PHP shell_exec() 运行可执行程序
- javascript - 如何在角度的简单对话框模型中从 api 调用返回值?
- docker - 如何在构建阶段将插件添加到 Neo4j Docker 容器,而不是在容器运行时下载插件?
- azure - 如何在 VS 2019 中使用 Azure 云资源管理器
- flutter - 如何在颤动中正确排列物品
- python - 正则表达式用相应的替换模式替换多个模式
- php - 用户未登录时显示登录/注册
- python - 使用 python 从 netCDF 读取特定位置的时间序列,时间以秒为单位