如何使用两个组件通过搜索进行过滤 [reactjs]
Posted
技术标签:
【中文标题】如何使用两个组件通过搜索进行过滤 [reactjs]【英文标题】:How to filter via search with two components [reactjs] 【发布时间】:2021-04-29 18:42:07 【问题描述】:需要card
组件与search
组件通信以过滤结果。
目前data
来自本地JSON文件,格式如下
[
"title": "example",
"description": "example",
"author": "example",
"date": "2021-01-01",
"featuredImage": "/example.jpg",
"categories": "example",
"tags": "example",
]
App.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;
搜索.js
import React from 'react';
const Search = ( onChange ) => (
<input
type='search'
placeholder='Search...'
className='search'
onChange=onChange
/>
);
export default Search;
卡片.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;
我对 React 钩子感到困惑。有人可以解释一下我在这个州做错了什么吗?
【问题讨论】:
我在你的App中看不到卡片功能组件。 React 可以将 props 从父组件传递给子组件。反之亦然。 我已经修改了代码。是的,您是正确的,但是我对如何更新状态以使搜索与卡片组件正常工作感到困惑。 更改const Card = ( props ) =>
和props.Result.map((x) => (
在您的卡片组件中尝试这种方式。
不起作用。当我 console.log 结果我得到一个空数组。
你能创建一个工作的 CodeSandbox 来演示你遇到的错误吗?
【参考方案1】:
我将数据添加到组件中以使您清楚
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/>
</>
);
;
我评论了有关代码的信息,以便您阅读它们
【讨论】:
以上是关于如何使用两个组件通过搜索进行过滤 [reactjs]的主要内容,如果未能解决你的问题,请参考以下文章