我不知道如何在不寫文章的情況下有效地表達這個問題。
我有這個接受 3 個道具的組件titleArr,title和boldIndexes。
基本概念是在渲染上述組件的一些組件中,將創建一個字串陣列。然后該陣列中的某些索引將作為boldIndexes道具傳遞。所述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
uj5u.com熱心網友回復:
您可以映射陣列并使用 回傳樣式部分,if以便您知道是否需要將其設為粗體。
titleArr.map((el, index) => {
if (index == 1 || index == 3) {
return "<StyledComponentBoldTitle>" el "</StyledComponentBoldTitle>"
} else {
return el;
}
});
uj5u.com熱心網友回復:
希望這能回答你的問題。
映射陣列時,測驗當前索引是否包含在粗體索引陣列中,如果是,則將 className 添加到您的跨度(我使用了跨度,因為它具有本機塊顯示)。
export const App2 = () => {
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 boldIndices = [1, 3];
return (
<>
{titleArr.map((text, idx) => {
const cls = boldIndices.includes(idx) ? "bold" : "";
// inside your stylesheet: .bold {font-weight: bolder}
return (
<span key={text} className={cls}>
{text}
</span>
);
})}
</>
);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/330756.html
標籤:javascript 数组 反应
