首页 > 解决方案 > 从字符串数组中,使用组件以不同的样式呈现字符串数组的某些索引

问题描述

如果不写论文,我不知道如何有效地表达这个问题。

我有这个组件接受 3 个道具titleArrtitleboldIndexes.

基本概念是在渲染上述组件的某些组件中,将创建一个字符串数组。然后该数组中的某些索引将作为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

标签: javascriptarraysreactjs

解决方案


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;
  }
});

推荐阅读