我想构建一个神奇宝贝搜索框,在用户输入时显示建议神奇宝贝。现在可以了,但我还想在显示整个神奇宝贝名称时突出显示搜索到的文本。
所以我基本上想用彩色文本替换普通的 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>
)
}
它的最佳实现是什么?任何建议表示赞赏
最佳答案
假设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>
)
}
关于javascript - React 在渲染之前为字符串的特定部分提供样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67349762/