首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在呈现之前为字符串的特定部分提供样式的反应?

在呈现之前为字符串的特定部分提供样式的反应?
EN

Stack Overflow用户
提问于 2021-05-02 02:43:16
回答 2查看 26关注 0票数 2

我想建立一个精灵宝可梦搜索框,显示建议精灵,而用户键入。现在,这是工作,但我也想突出显示搜索文本时,显示整个精灵宝可梦名称。

所以我基本上是想用彩色文本替换纯searchedText。我试着在下面和其他一些方法中替换它,但我不能让它工作。它显示了[Object object]<remaining text>

文本将在开头、中间或结尾。

代码语言:javascript
复制
 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>
        )
    }

它的最佳实现是什么?欢迎提出任何建议。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-05-02 03:03:00

假设searchedText是一个字符串,并且它总是在name中恰好出现一次。

代码语言:javascript
复制
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>
  )
}
票数 2
EN

Stack Overflow用户

发布于 2021-05-02 03:01:15

将你的文本分成3部分:

代码语言:javascript
复制
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>
  )
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67349762

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档