• 我正在使用react-highlight-words包来突出显示在文本框中输入的文本
  • 我提到了react-highlight-words文档,因为它们将searchWords作为数组传递。 https://www.npmjs.com/package/react-highlight-words
  • ,但问题是当我将其传递给数组let searchBarText = [];时,我遇到了错误searchWords.filter不是函数。
  • 您能告诉我如何修复它,以便将来我自己修复。
  • 在下面提供我的沙箱和代码段。

  • https://codesandbox.io/s/00nm6k8orp
    class SearchBar extends React.Component {
      constructor() {
        super();
        this.state = {
          // testHighlight: {}
          testHighlight: []
        };
        this.handleChange = this.handleChange.bind(this);
      }
    
      handleChange(e) {
        console.log(e.target.value); // your search bar text
        let object = document.getElementById("myDiv");
        console.log(object.textContent); // your div text
    
        // now that you have the two strings you can do your search in your favorite way, for example:
        let searchBarText = [];
        searchBarText = e.target.value;
        console.log("searchBarText --->", searchBarText);
    
        let divText = object.textContent;
        console.log("divText --->", divText);
    
        if (divText.includes(searchBarText)) {
          console.log("the div text contains your search text");
        } else {
          console.log("the div text doesn't contain search text");
        }
    
        // this.setState({ testHighlight: response.data });
    
        this.setState({ testHighlight: searchBarText });
      }
    
      render() {
        return (
          <div>
            <input
              type="text"
              className="input"
              onChange={this.handleChange}
              placeholder="Search..."
              // highlightText={this.handleChange}
              testHighlight={this.state.testHighlight}
            />
    
            <HighlighterImplementation testHighlight={this.state.testHighlight} />
          </div>
        );
      }
    }
    

    最佳答案

    SearchBar.js文件中,您正在将testHighlight更新为字符串:

    this.setState({ testHighlight: searchBarText });
    

    您不是要这样做:
     this.setState({ testHighlight: [searchBarText] });
    

    或者,如果要将其添加到现有阵列中:
    this.setState({ testHighlight: [...this.state.testHighlight, searchBarText] });
    

    关于javascript - searchWords.filter不是函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54201939/

    10-09 14:05