我对Reactjs很陌生。我正在尝试实现一个应用程序,其中数据显示在主页上,并且其中包含选项。单击选项后,应相应地过滤数据,并且过滤后的数据应替换原始数据。
有人可以帮我实现这一目标吗?
答案 0 :(得分:0)
这是@Priscilla的非常简单的示例:
import React, { useState } from "react";
import "./styles.css";
const categories = ["cat1", "cat2", "cat3"];
const products = [
{ id: "1", name: "Product 1", category: "cat1" },
{ id: "2", name: "Product 2", category: "cat1" },
{ id: "3", name: "Product 3", category: "cat1" },
{ id: "4", name: "Product 4", category: "cat2" },
{ id: "5", name: "Product 5", category: "cat2" },
{ id: "6", name: "Product 6", category: "cat2" },
{ id: "7", name: "Product 7", category: "cat3" },
{ id: "8", name: "Product 8", category: "cat3" },
{ id: "9", name: "Product 9", category: "cat3" },
{ id: "10", name: "Product 10", category: "cat3" }
];
export default function App() {
const [filteredProducts, setFilteredProducts] = useState([]);
const filterProducts = function (event) {
const prods = products.filter((p) => p.category === event.target.value);
console.log(prods);
setFilteredProducts(prods);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<select onChange={(event) => filterProducts(event)}>
<option value="">-- Select --</option>
{categories.map((c) => (
<option key={c} value={c}>
{c}
</option>
))}
</select>
<ul>
{filteredProducts.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
</div>
);
}
您可以在这里使用它:https://codesandbox.io/s/crimson-bush-urssn?file=/src/App.js