我有一个搜索词,并根据搜索词显示相应的结果。尝试突出显示在结果列表中搜索的关键字。但它给了我空虚的价值。
这是我试过的:
render() {
const { label } = this.props;
const { searchResults, query } = this.state;
let textHighlighter;
return (
<div>
<form>
<input placeholder={label} ref={input => (this.search = input)} onChange={e => this.handleInputChange(e)} />
</form>
{searchResults &&
searchResults.results &&
searchResults.results.length > 0 && (
<ul>
{searchResults.results.map((result, i) => {
let searchKeywordIdx = result.indexOf(query);
if (searchKeywordIdx > -1) {
textHighlighter = [
result.substring(0, searchKeywordIdx),
<strong key={i}>
{result.substring(searchKeywordIdx, searchKeywordIdx + query.length).substring(searchKeywordIdx + query.length)}
</strong>
];
}
return <li key={result}>{textHighlighter}</li>;
})}
</ul>
)}
</div>
);
}
注意:this.state.query =&#34; aaa&#34;
示例JSON:
searchResults.results = [“aaa”, “aaa bbb”, “aaa ccc”]
所以我需要突出显示结果列表中的所有"aaa"
。
答案 0 :(得分:1)
https://codepen.io/smilesaayush/pen/NzgRmW?editors=0010 修复了textHighlighter中的一个小问题。
return (
<div>
{searchResults &&
searchResults.results &&
searchResults.results.length > 0 && (
<ul>
{searchResults.results.map((result, i) => {
let searchKeywordIdx = result.indexOf(query);
if (searchKeywordIdx > -1) {
textHighlighter = [
result.substring(0, searchKeywordIdx),
<strong key={i}>
{result.substring(searchKeywordIdx, searchKeywordIdx + query.length)}
</strong>,
result.substring(searchKeywordIdx + query.length)
];
}
return <li key={result}>{textHighlighter}</li>;
})}
</ul>
)}
</div>
);