嗨,所以我有一些数据,我想使用钩子搜索和过滤。我能够加载初始列表,但我不知道如何搜索数组,如果输入文本与数组中的文本匹配,则显示与输入文本匹配的数组文本。 我尝试使用过滤器和其他东西,但对如何将它们放在一起感到困惑。我需要的数据可以通过使用props.data.map((e) => e.name)
import React, { useState } from "react";
import CharacterCard from "./CharacterCard";
import CharacterList from "./CharacterList";
export default function SearchForm(props) {
console.log(props.data.map((e) => e.name));
let hi = []
props.data.map((e) => hi.push(e.name))
const [search, setSearch] = useState('');
const check = () => {
if(search === ''){
return <CharacterCard data={props.data} />
} else if (hi.indexOf(search) === -1 ){
return <CharacterCard data={props.data} />
} else {
return <h1>{I want this to be anything that matches the input bot value}</h1>
}
}
let handleChange =(e) => {
setSearch(e.target.value)
}
return (
<section className="search-form">
<input type="text" onChange={handleChange} value={search} />
{check()}
</section>
);
}
你走在正确的轨道上,你只需要修改你的check
函数。此示例将呈现名称开头部分匹配的所有名称的列表:
const check = () => {
// get array of all names in `props.data`
const names = props.data.map(e => e.name);
// this will filter out any names that do not start with the content of `search`
// leaving us with an array of matching names
const searchMatches = names.filter(name => name.startsWith(search));
// do something with the results `searchMatches`
// (this example returns a list of names)
return <ul>{searchMatches.map(name => <li key={name}>{name}</li><ul>
})