我想建立一个精灵宝可梦搜索框,显示建议精灵,而用户键入。现在,这是工作,但我也想突出显示搜索文本时,显示整个精灵宝可梦名称。
所以我基本上是想用彩色文本替换纯searchedText。我试着在下面和其他一些方法中替换它,但我不能让它工作。它显示了[Object object]<remaining text>
文本将在开头、中间或结尾。
const PokemonProfile = ({name, searchedText}) => {
const fullStr = name.replace(searchedText, <span style='background-color: rgba(0, 255, 0, 0.3)'> {searchedText} </span>)
return (
<div>
<h4 className='PokemonProfile'> {fullStr} </h4>
</div>
)
}它的最佳实现是什么?欢迎提出任何建议。
发布于 2021-05-02 03:03:00
假设searchedText是一个字符串,并且它总是在name中恰好出现一次。
const PokemonProfile = ({
name,
searchedText
}) => {
const [before, after] = name.split(searchedText);
return (
<div>
<h4 className="PokemonProfile">
<span>{before}</span>
<span style={{ backgroundColor: "rgba(0, 255, 0, 0.3)" }}>
{searchedText}
</span>
<span>{after}</span>
</h4>
</div>
)
}发布于 2021-05-02 03:01:15
将你的文本分成3部分:
const PokemonProfile = ({name, searchedText}) => {
const start = name.indexOf(searchedText);
const end = start + searchedText.length;
const firstPart = name.substr(0, start);
const lastPart = name.substr(end);
return (
<div>
<h4 className='PokemonProfile'>
<span>{firstPart}</span>
<span style={{ backgroundColor: "rgba(0, 255, 0, 0.3)"}}>{searchedText}</span>
<span>{lastPart}</span>
</h4>
</div>
)
}https://stackoverflow.com/questions/67349762
复制相似问题