如何在React.JS中添加搜索过滤器?

时间:2019-07-11 16:50:58

标签: javascript reactjs search

我正在React.js中构建电影角色列表以进行练习。我在组件中添加了一些字符,但我想在页面顶部使用“搜索”过滤器。如何在该项目中添加搜索过滤器组件?

这是我的App.js;

import React from 'react';
import './App.css';
import CharacterCard from './CharacterCard.js';

function App() {
  return (
    <div className="characters">

      <CharacterCard 
          name="Berlin" 
          imgUrl="https://m.media-amazon.com/images/M/MV5BMGE4YTZiZDgtMjQyNC00ZTA0LWI3M2UtNmFiYmUzZGRmNWU5XkEyXkFqcGdeQXVyNDg4MjkzNDk@._V1_.jpg" 
          quote="Right now I'm a bit busy." 
      />

      <CharacterCard 
          name="Tokyo" 
          imgUrl="https://m.media-amazon.com/images/M/MV5BYjY3MTk2YzUtMWRjMS00MmE1LWEyNTYtMjdkZjM1MmMwNWE4XkEyXkFqcGdeQXVyOTc1NDAzOTI@._V1_.jpg" 
          quote="After all, love is a good reason to make everything go wrong." 
      />

      <CharacterCard 
          name="Professor" 
          imgUrl="https://m.media-amazon.com/images/M/MV5BMDk0M2RlZTYtNWIxZi00ZDQ1LWI3ZTItYjRmMTA5MGIxZmE2XkEyXkFqcGdeQXVyMzQ3Nzk5MTU@._V1_.jpg" 
          quote="Nine hundred and eighty for million euros." 
      />

      <CharacterCard 
          name="Rio" 
          imgUrl="https://m.media-amazon.com/images/M/MV5BZjM3OWZhYzMtMTM4OS00YjA2LWFlYjItZTk2NTI1YmU3YTUwXkEyXkFqcGdeQXVyNDg4MjkzNDk@._V1_.jpg" 
          quote="I'm not a kid." 
      />

      <CharacterCard 
          name="Denver" 
          imgUrl="https://fotografias-nova.atresmedia.com/clipping/cmsimages01/2018/04/13/82FD1AE1-5210-466B-8346-9277965A0C4F/58.jpg" 
          quote="Here is a wonderful place for sleep, Dad." 
      />

      <CharacterCard 
          name="Moscow" 
          imgUrl="https://m.media-amazon.com/images/M/MV5BYmE0YTBhYmUtYzQ1ZC00ZGFkLWI0ZjctNmU2NDI3ODAzMWIzXkEyXkFqcGdeQXVyNDg4MjkzNDk@._V1_.jpg" 
          quote="It was a pleasure to get to know you." 
      />

    </div>
  );
}

export default App;

这是我的CharacterCard.js;

import React from 'react'

function CharacterCard(props) {
    return(
          <div className="character-card">
            <img src={props.imgUrl}/>
            <h3 className="character-name">{props.name}</h3>
            <p>{props.quote}</p>
          </div>
        )
}

export default CharacterCard

2 个答案:

答案 0 :(得分:0)

您可以使用组件搜索-

state = {
        query: '',
        characterArray: [// the value you want to make searchable],
        characterSuggestion: [],
    };

handleInputChange = () => {
        this.setState({
            query: this.search.value
        }, () => {
            if (this.state.query && this.state.query.length > 1) {
                if (this.state.query.length % 2 === 0) {
                    this.getCharacterSuggestion();
                }
            } 
        })
    };

getCharacterSuggestion = () => {
        const {characterArray, query} = this.state;

        this.setState({
            characterSuggestion: characterArray.filter((character) => character.toLowerCase().includes(query.toLowerCase()))
        })
    };

<div>
            <form>
                <input
                    placeholder="Search for Character"
                    ref={input => this.search = input}
                    onChange={this.handleInputChange}
                />
                <p>{this.state.query}</p>
            </form>

            <Suggestions characterSuggestion={characterSuggestion}/>
            </div>

在“建议”组件中-

const Suggestions = (props) => {
    const options = props.characterSuggestion.map((characterSuggestion, index) => (
        <li key={index}>
            {characterSuggestion}
        </li>
    ));
    return <ul>{options}</ul>
};

这是创建搜索组件的基本思想。如果需要,可以使其更精美。

答案 1 :(得分:0)

您可以将值过滤器保持在组件状态,并使用它来查看它是否作为子字符串包含在任何数组元素属性中。

    class App extends React.Component {
  state = {
    filter: "",
    data: [
      {
        fname: "Jayne",
        lname: "Washington",
        email: "jaynewashington@exposa.com",
        gender: "female"
      },
      {
        fname: "Peterson",
        lname: "Dalton",
        email: "petersondalton@exposa.com",
        gender: "male"
      },
      {
        fname: "Velazquez",
        lname: "Calderon",
        email: "velazquezcalderon@exposa.com",
        gender: "male"
      },
      {
        fname: "Norman",
        lname: "Reed",
        email: "normanreed@exposa.com",
        gender: "male"
      }
    ]
  };

  handleChange = event => {
    this.setState({ filter: event.target.value });
  };

  render() {
    const { filter, data } = this.state;
    const lowercasedFilter = filter.toLowerCase();
    const filteredData = data.filter(item => {
      return Object.keys(item).some(key =>
        item[key].toLowerCase().includes(lowercasedFilter)
      );
    });

    return (
      <div>
        <input value={filter} onChange={this.handleChange} />
        {filteredData.map(item => (
          <div key={item.email}>
            <div>
              {item.fname} {item.lname} - {item.gender} - {item.email}
            </div>
          </div>
        ))}
      </div>
    );
  }
}