React:如何根据关键字将字符串数组中的单词加粗



假设我有一个值数组,我需要对其进行筛选,并根据keyword搜索返回所有值,然后返回3个结果。

var fruits = ["Banana", "Orange", "Apple", "Mango", "Peach"];
array = array.filter(item => {
return item.toLowerCase().indexOf(term) > -1;
}).slice(0, 3)

我遇到的问题是将搜索到的每个项目的术语加粗。例如,如果我搜索";a";,我应该返回一个jsx代码数组;a";在结果中列出,它是粗体的:

[
<span>B<strong>a</strong>n<strong>a</strong>n<strong>a</strong></span>,
<span>Or<strong>a</strong>nge</span>,
<span><strong>A</strong>pple</span>
]

我已经尝试了一些效果:

array = array.map((item, index) => (
<span>
{item.split('a')} // then somehow join the a back with the strong tags
</span>
));

也尝试过类似的方法,但返回的值是字符串格式的,据我所知无法转换为jsx:

array.map(item => {
return item.replace(new RegExp('(' + term + ')', 'ig'), '<strong>$1</strong>');   
});

非常感谢您的帮助。

非常接近,您需要检查数组的元素是否具有搜索项,然后将元素拆分为字母以匹配该项(https://stackblitz.com/edit/react-earc4c)

import React from 'react';
export default function App() {
var fruits = ['Banana', 'Orange', 'Apple', 'Mango', 'Peach', 'Blueberry'];
return (
<div style={{ backgroundColor: 'palegoldenrod' }}>
{fruits.map(fruit => {
if (/a/.test(fruit)) {
return (
<p>
{fruit.split('').map(letter => {
if (letter === 'a') {
return <strong>{letter}</strong>;
}
return letter;
})}
</p>
);
}
return fruit;
})}
</div>
);
}

@hunter-mcmillen为我指明了正确的方向,这让我找到了解决方案,所有的功劳都归于他!!!我可能有点歪曲了我的问题。。。如果这个词有字母";a";下面是我想要的,再次感谢亨特!!!

import React from 'react';
export default function App() {
var fruits = ['Banana', 'Orange', 'Apple', 'Mango', 'Peach', 'Blueberry'];
return (
<div style={{ backgroundColor: 'palegoldenrod' }}>
{fruits.map(fruit => {
if (/a/.test(fruit)) {
return (
<p>
{fruit.split(' ').map(word => {
if (word.indexOf('a') != -1) {
return <strong>{word}</strong>;
}
return word;
})}
</p>
);
}
return fruit;
})}
</div>
);
}

我还想提到我的一个朋友用不同的方法解决了这个问题:

let term = 'apple orange banana';
let search = 'a';

let parts = term.split(search);

return parts.map((item, i) => (
<>{item && <strong>{item}</strong>}{(i !== parts.length - 1) ? search : null}</>
))

最新更新