[英]How to filter via search with two components [reactjs]
Need the card
component to communicate with the search
component to filter results.需要
card
组件与search
组件通信以过滤结果。
At the moment the data
comes from a local JSON file with the following format目前
data
来自本地 JSON 文件,格式如下
[
{
"title": "example",
"description": "example",
"author": "example",
"date": "2021-01-01",
"featuredImage": "/example.jpg",
"categories": "example",
"tags": "example",
}
]
App.js应用程序.js
import React, { useState } from 'react';
import Card from './components/Card';
import Search from './components/Search';
import Data from './data/data.json';
import './App.css';
const App = () => {
const [DataFile, setDataFile] = useState(Data);
const [Search, setSearch] = useState('');
const [Result, setResult] = useState([]);
const searchChange = (e) => {
setSearch(e.target.value);
};
const onSearch = () => {
setResult(Data);
};
return (
<>
<Search onChange={searchChange} onSearch={onSearch} />
<Card data={DataFile} Result={Result} />
</>
);
};
export default App;
Search.js搜索.js
import React from 'react';
const Search = ({ onChange }) => (
<input
type='search'
placeholder='Search...'
className='search'
onChange={onChange}
/>
);
export default Search;
Card.js Card.js
import React from 'react';
const Card = ({ data }) => {
return (
<div className='container'>
{data.map((x) => (
<div >
<h1>{x.title}</h1>
</div>
))}
</div>
);
};
export default Card;
I've confused myself with the React hooks.我对 React 钩子感到困惑。 Could someone please explain what I'm doing wrong with the state?
有人可以解释一下我在 state 上做错了什么吗?
i added the data to component to make it clear for you我将数据添加到组件中以使您清楚
const App = () => {
//here we define data
const data = [
{
"title": "example",
"description": "example",
"author": "example",
"date": "2021-01-01",
"featuredImage": "/example.jpg",
"categories": "example",
"tags": "example",
}
]
//here is where we keep search result
const [Result, setResult] = useState(null);
//here we filter the list where the title(or any element of data) is equal to input value
const searchChange = (e) => {
const searchResult = data.filter((element) => element.title
.includes(e.target.value))
//here we set the filtered list to result
setResult(searchResult);
};
return (
<>
<Search onChange={searchChange}/>
//here we check if result exists if yes pass it to card else pass the data instead
<Card data={Result!==null?Result:data}/>
</>
);
};
i commented the information about the code so you can read them我评论了有关代码的信息,因此您可以阅读它们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.