首页 > 解决方案 > 如何对此名称进行实时搜索反应js?

问题描述

我正在尝试对表中的名称进行实时搜索,但我无法进行实时搜索我不知道该怎么做我像我提到的那样编写了我的代码请帮助我如何在名称字段敌人表上进行实时搜索在Search页面中我onSubmit={this.props.loaddata这样使用谢谢

import React, { Component } from "react";
import Search from "../../views/Cars/Search";

class Search1 extends Component {
  constructor(props) {
    super(props);
    this.state = {
      query: []
    };
  }

  // Get Data from filter date
  getData = async e => {
    try {
      const search = e.target.elements.search.value;
      e.preventDefault();
      const res = await fetch(`https://swapi.co/api/people/?search=${search}`);
      const query = await res.json();
      console.log(query);
      this.setState({
        query: query.results
      });
    } catch (e) {
      console.log(e);
    }
  };

  async componentDidMount() {
    // let authToken = localStorage.getItem("Token");
    try {
      const res = await fetch(`https://swapi.co/api/people/`);
      const query = await res.json();
      // console.log(movie);
      this.setState({
        query: query.results
      });
    } catch (e) {
      console.log(e);
    }
  }

  render() {
    const options = this.state.query.map(r => <li key={r.id}>{r.name}</li>);
    return (
      <div>
        <Search loaddata={this.getData} />
        {options}
      </div>
    );
  }
}

export default Search1;

标签: javascriptreactjslivesearch

解决方案


一般你可以试试 React-Search

  import Search from 'react-search'
  import ReactDOM from 'react-dom'
  import React, { Component, PropTypes } from 'react'

  class TestComponent extends Component {

  HiItems(items) {
     console.log(items)
  }

  render () {
     let items = [
        { id: 0, value: 'ruby' },
        { id: 1, value: 'javascript' },
        { id: 2, value: 'lua' },
        { id: 3, value: 'go' },
        { id: 4, value: 'julia' }
     ]

     return (
        <div>
        <Search items={items} />

        <Search items={items}
                 placeholder='Pick your language'
                 maxSelected={3}
                 multiple={true}
                 onItemsChanged={this.HiItems.bind(this)} />
        </div>
     )
  }
  }

推荐阅读