首页 > 解决方案 > 我正在尝试在 React 中实现搜索过滤器,但它不起作用,你能帮帮我吗?

问题描述

我是 React 的新手,我正在尝试构建一个获取 API 的搜索过滤器,控制台没有给我任何错误,但是过滤器搜索栏不起作用,有人可以帮我吗?谢谢!

所以,我认为一切都应该没问题,因为在 chrome 控制台中,我没有收到任何错误,但 SearchBox.js 似乎不起作用

这是代码:

搜索框.js:

import React from 'react';

class SearchBox extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      suggestions: [],
      text: '',
    }
  }

  componentDidMount() {
    fetch('https://api.scryfall.com/catalog/card-names')
    .then(response => response.json())
    .then(cards => this.setState({ suggestions: cards.data}))
  }

  onTextChanged = (event) => {
    const { items } = this.props;
    const value = event.target.value;
    let suggestions = [];
    if (value.length > 0) {
      const regex = new RegExp(`^${value}`, '');
      suggestions = Object.keys(items).sort().filter(word => regex.test(word))
  }
  this.setState(() => ({ suggestions, text: value }))
}

suggestionSelected (value) {
  this.setState({
    text: value,
    suggestions: []
  });
}


renderSuggestions () {
  const { suggestions } = this.state;
  if (suggestions.length === 0) {
    return null;
  }
  return (
    <ul>
      {suggestions.map((item, index) => <li key={index} onClick={() => this.suggestionSelected(item)}>{item}</li>)}
    </ul>
  )
}

  render () {
    const { text } = this.state;
    return (
      <div>
        <input value={text}
          onChange={this.onTextChanged} type="text" />
          {this.renderSuggestions()}
      </div>
    );
  }
}


export default SearchBox;

应用程序.js:

import React from 'react';

import SearchBox from './components/SearchBox';
class App extends React.Component{

  render() {
    return(
      <div>
        <SearchBox items/>
      </div>
    )
  }
};

export default App;


标签: javascriptreactjs

解决方案


您缺少函数绑定:

class SearchBox extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      suggestions: [],
      text: '',
    }

    // == Binding ==
    this.suggestionSelected = this.suggestionSelected.bind(this);
    this.renderSuggestions = this.renderSuggestions.bind(this);
    this.onTextChanged = this.onTextChanged.bind(this);
    // == ======= ==

  }

// [...]

}

推荐阅读