简体   繁体   English

如何将输入文本传递给我的 React 应用程序中的过滤器组件

[英]How can i pass the input text to the filter component in my React application

I am trying to build an application using "rick and morty API" where there is list of characters with various parameters such as gender,alive status,image etc.我正在尝试使用“rick and morty API”构建一个应用程序,其中包含具有各种参数的字符列表,例如性别、生存状态、图像等。

What i am trying to do: 1) I am trying to create a search bar, so that i can search names from the list of 493 characters.我正在尝试做的事情: 1)我正在尝试创建一个搜索栏,以便我可以从 493 个字符的列表中搜索名称。

My CardList.js component:我的 CardList.js 组件:

import React from "react";
import axios from "axios";
import Card from "./Card";

class CardList extends React.Component {
  state = {
    // url: `https://rickandmortyapi.com/api/character/${[...Array(494).keys()]}`,
    character: []
  };

  async componentDidMount() {
    //const res = await axios.get(this.state.url);
    const ids = Array(493)
      .fill(null)
      .map((_, idx) => idx + 1)
      .join(","); // '1,2,3...,300'
    const url = `https://rickandmortyapi.com/api/character/[${ids}]`;
    const res = await axios.get(url);

    this.setState({
      character: res.data
    });
  }

  handleChange(e) {
    e.preventDefault();
    let typedValue = e.target.value;
    console.log(typedValue);
  }

  render() {
    let filter = this.state.character.filter(function(e) {
      return e.name.includes("Pickle Rick");
    });

    return (
      <div>        
        <form>
          <input type="text" name="title" onChange={this.handleChange} />          
        </form>

        {filter.map(character => (
          <Card
            key={character.id}
            imgURL={character.image}
            id={character.id}
            name={character.name}
            status={character.status}
            species={character.species}
            gender={character.gender}
            type={character.type ? character.type : "Unknown"}
          />
        ))}
      </div>
    );
  }
}

export default CardList;

In my filter method i have hard-coded the name of one of the characters as "Pickle Rick", but i want to pass "event.target.value", so that it can match up the value and can render the exact card which matches only.在我的过滤方法中,我将其中一个字符的名称硬编码为“Pickle Rick”,但我想传递“event.target.value”,以便它可以匹配该值并可以呈现确切的卡片只匹配。 How can I do that?我怎样才能做到这一点? Help me out, please!请帮帮我!

You can set the typedValue in your state.您可以在typedValue中设置 typedValue。

handleChange = e => {
    e.preventDefault();
    let typedValue = e.target.value;
    this.setState({typedValue});
}

When you are initializing state you can initialize this typedValue with an empty string当您初始化 state 时,您可以使用空字符串初始化此typedValue

this.state = {
    character: [],
    typedValue: ''
};

And in your render you can use these values from state在您的渲染中,您可以使用 state 中的这些值

render() {
    const {character, typedValue} = this.state
    let filter = character.filter(char => char.name.includes(typedValue));
    // ...
}

You can create another array in the state您可以在 state 中创建另一个数组

state = {
  character: [],
  filteredCharacter: [], //for filtered list
}

Now in the handleChange you can add the following code现在在handleChange中你可以添加以下代码

  handleChange(e) {
     e.preventDefault();
     const { character } = this.state;
     let typedValue = e.target.value;
     let filteredCharacter = character.filter(char => char.includes(typedValue))
     this.setState({filteredCharacter}) 
  }

Now you can directly user filteredCharacter inside render method现在您可以在render方法中直接使用用户filteredCharacter字符

In my opinion why don't you set one state for setting the character.在我看来,你为什么不设置一个 state 来设置角色。

Like: -喜欢: -

state = { state = {

character: [],
typedValue: '',

}; };

handleChange(e) {处理变化(e){

e.preventDefault();
let typedValue = e.target.value;
this.setState({typedValue});

} }

Then inside render method: -然后在渲染方法中: -

render() {使成为() {

let filter = this.state.character.filter(function(e) {让过滤器= this.state.character.filter(函数(e){

  return e.name.includes(this.state.typedValue);

});

} }

I hope this answer your question.我希望这能回答你的问题。

Your method could be:你的方法可能是:

    async handleChange (e) {
        e.preventDefault();
        const typedValue = e.target.value;
        const url = `https://rickandmortyapi.com/api/character/?name=${typedValue}`;
        const res = await axios.get(url);
        // now render the result    
      }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我无法在React应用程序中修改SVG组件 - I can't modify my SVG component in my React Application 我将如何重组我的React App,以便可以将状态传递给另一条路线上的组件 - How would I restructure my React App, so that I can pass state down to a component on a different route 如何将组件作为道具传递给 React 中的另一个组件? - How can I pass a component as a prop into another component in React? 我如何创建一个简单的 React 组件,呈现为<div>它将文本值和前景色作为输入 - How I can create a simple React component rendered as a <div> which takes a text value and a foreground color as input React - 如何将值传递给组件中的过滤功能? - React - How to pass value to filter function in component? 如何在我的 React 组件中结合 onBlur 和 onFocus 而不重新选择我输入的每个字母上的文本? - How can I combine onBlur and onFocus in my React Component without reselecting the text on every letter I type in? 我的反应组件上输入文本的占位符不支持: - Placeholder of input text on my react component is not supporting: 如何在 React 组件道具上使用 filter 方法? - How can I use the filter method on a React component prop? 如何在React中不带道具的情况下将数据传递给组件? - How can I pass data to a component without props in React? 如何将带有对象的javascript文件传递到react组件中 - How can I pass a javascript file with an object into a react Component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM