javascript - 从字符串数组中,使用组件以不同的样式呈现字符串数组的某些索引
问题描述
如果不写论文,我不知道如何有效地表达这个问题。
我有这个组件接受 3 个道具titleArr
,title
和boldIndexes
.
基本概念是在渲染上述组件的某些组件中,将创建一个字符串数组。然后该数组中的某些索引将作为boldIndexes
道具传递。prop 是字符串的title
初始数组,转换为字符串。
一个例子如下
const personal = 5;
const friends = 1;
const titleArr = [
'You currently have ',
// this item will be bold
personal > 0 ? `${personal} saved item${personal > 1 ? 's' : ''} ` : null,
friends > 0 ? `${personal > 0 ? 'and ' : ''}` : '. ',
// this item will be bold
friends > 0 ? `${friends} item${friends > 1 ? 's' : ''} ` : null,
friends > 0 ? 'saved by your friends.' : null,
];
const boldIndexes = [titleArr[1], titleArr[3]];
const title = titleArr.join('');
所以在上面的例子中
标题Arr
[
'You currently have ',
'5 saved items',
'and ',
'1 item',
'saved by your friends.',
]
粗体索引
[
'5 saved items',
'1 item',
]
标题
'You currently have 5 saved items and 1 item saved by your friends.',
在我的组件中,我想要以下内容;
<StyledComponentTitle>
You currently have
<StyledComponentBoldTitle>5 saved items</StyledComponentBoldTitle>
and
<StyledComponentBoldTitle>1 item</StyledComponentBoldTitle>
saved by your friends.
</StyledComponentTitle>
或者
<StyledComponentTitle>
You currently have
</StyledComponentTitle>
<StyledComponentBoldTitle>
5 saved items
</StyledComponentBoldTitle>
<StyledComponentTitle>
and
</StyledComponentTitle>
<StyledComponentBoldTitle>
1 item
</StyledComponentBoldTitle>
<StyledComponentTitle>
saved by your friends.
</StyledComponentTitle>
这是否可以实现而无需做dangerouslySetInnerHTML
解决方案
You can map the array and return the styled part with an if
so you know if you need to make it bold or not.
titleArr.map((el, index) => {
if (index == 1 || index == 3) {
return "<StyledComponentBoldTitle>" + el + "</StyledComponentBoldTitle>"
} else {
return el;
}
});
推荐阅读
- apama - 来自 Cumulocity 中内置 Apama 运行时的 HTTP 请求的凭据
- android - 从 Fragment 到 recyclerview 的共享元素转换
- c# - Automapper 将源属性映射到某些目标属性
- flutter - 如何在颤动中使用带有迷你图的共享偏好?
- html - 在 PHP SQL 显示的列中居中文本
- sql-server - SQL Server 网络接口库无法取消注册服务主体名称 (SPN)
- windows - 如何找到加载的asr移动代理驱动的版本?
- git - 如何使用 ssh auth 在代码提交存储库上使用 go get 命令?
- git - 如何在git中只提交一个组件javascript文件
- vue.js - `vb-modal` 和 `vb-toggle` 等属性如何工作?他们在哪里听?