突出显示有关类型react的搜索文本 [英] highlight searching text on type react

查看:85
本文介绍了突出显示有关类型react的搜索文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在输入时突出显示输入中的文本,在这种情况下,我使用两种方法.据我了解,我需要返回类似以下的内容:<mark>${item}<mark/>

I try to highlight text in a input on typing, I use two method in this case. As I understand I need return on search something like this: <mark>${item}<mark/>

fuzzyContains = (text, search) => {
        debugger
        if (!text)
            return false
        if (!search)
            return true

        search = search.toLowerCase()
        text = text.toString().toLowerCase()

        let previousLetterPosition = -1

        return search.split('').every(s => {
            debugger
            previousLetterPosition = text.indexOf(s, previousLetterPosition + 1)

            return previousLetterPosition !== -1
        })
    }

    handleSearch = search => {
        const {data} = this.state
        debugger
        let filteredData = data.filter(x => Object.keys(x).some(key => {
            debugger
            this.fuzzyContains(x[`<mark>${key}<mark/>`], search)}))

        this.setState({filteredData, search})
    }

推荐答案

您提供的代码太少,无法理解应用程序中实际发生的事情.相反,我在下面做了一个简单的例子.

The code you provide is too little to understand what's actually going on in your app. Instead, I have made a simple example below.

在以下代码段中,我首先创建一个带有固定文本和输入元素的应用程序.输入元素具有一个具有onChange触发器的侦听器.每当您键入内容时,都会触发changeInput函数.

In the following snippet I start by creating an application with a fixed text and an input element. The input element has a listener that has an onChange trigger. Whenever you type something, the changeInput function is fired.

此函数通过获取打印文本的相关DOM节点的innerText开始.然后,它尝试使用indexOf查找您输入的子字符串.如果存在匹配项,我们将字符串分成三部分(匹配的文本,以及该匹配的文本之前和之后的子字符串,如果有的话).

The function starts by getting the innerText of the related DOM node where the text is printed. It then tries to find your entered substring with indexOf. If there's a match, we split the string into three pieces (the matching text, and the substrings before and after that matching text, if any).

如果没有匹配项,我们将文本重置为初始值.

If there is no match, we reset the text back to the initial value.

然后将整个对象输入一个数组;第一项和第三项是纯字符串,而第二项(匹配项)是类型为strong的React元素,用于突出显示匹配的文本.

The whole thing is then entered into an array; the 1st and 3rd items are plain strings, whereas the 2nd item (the match) is a React Element of type strong which is used to highlight the matching text.

class MyApp extends React.Component {
  constructor() {
    super();
    this.initialText = "Lorem ipsum dolor sit amet";
    this.state = {
      text: this.initialText,
      inputValue: ""
    };
  }
  changeInput = (e) => {
    let value = e.target.value;
    let txt = document.getElementById("myText").innerText;
    let idx = txt.indexOf(value);
    if(idx >= 0) {
      let newText = [txt.substring(0, idx), <strong>{txt.substring(idx, idx + value.length)}</strong>, txt.substring(idx + value.length)];
      this.setState({inputValue: value, text: newText});
    } else {
      this.setState({inputValue: value, text: this.initialText});
    }    
  }
  render() {
    return (
      <div>
        <p id="myText">{this.state.text}</p>
        <input onChange={this.changeInput} value={this.state.inputValue} />
      </div>
    );
  }
}

ReactDOM.render(<MyApp />, document.getElementById("app"));

strong {
  background: red;
  color: white;
  font-weight: inherit;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

请注意,如果愿意,可以使用refs完成此操作.如果要避免DOM查找和refs的使用,则可以始终使用2个状态变量.一个保存结果JSX,另一个保存纯文本表示.

Note that this can be done with using refs if you prefer. If you want to avoid DOM lookups and the use of refs, you could always use 2 state variables; one that holds the resulting JSX and one that holds the plain text representation.

还要注意,这只会突出显示第一个匹配子字符串.例如,如果您具有字符串:"Lorem ipsum,Lorem ipsum" ,并且搜索了"Lorem" ,则仅会突出显示该单词的首次出现.如果您希望获得更多关注,可以尝试使用某种正则表达式.

Also note that this will only highlight the first matching substring. For example, if you had the string: "Lorem ipsum, Lorem ipsum", and you searched for "Lorem", only the first occurrence of that word would be highlighted. If you want multiple hightlights, you could try using some kind of regex.

这篇关于突出显示有关类型react的搜索文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆