[英]How to filter a table with select options in React (component function)
關閉。 這個問題需要細節或清晰。 它目前不接受答案。 添加詳細信息並闡明您正在解決的問題。 這將幫助其他人回答問題。 您可以編輯問題或發布新問題。
4 分鍾前關閉。
我找不到如何使用 Select(下拉菜單)在 React 中過濾表。 我在 Google 上找到了一個示例,但他們使用了 Node,但他們的代碼不適用於我的 React 應用程序。 我更喜歡使用組件而不是 class 功能。 這是我的代碼。 我想通過 select 選項過濾表格示例???:
const [data, getData] = useState([])
const URL = 'https://jsonplaceholder.typicode.com/posts'
useEffect(() => {
fetchData()
}, [])
const fetchData = () => {
fetch(URL)
.then((res) =>
res.json())
.then((response) => {
console.log(response);
getData(response);
})
}
return (
<>
<Select options=["A","B","C"] />
<table>
<tr>
<th>User Id</th>
<th>Id</th>
<th>Title</th>
<th>Description</th>
</tr>
{data.map((item, i) => (
<tr key={i}>
<td>{item.userId}</td>
<td>{item.id}</td>
<td>{item.title}</td>
<td>{item.body}</td>
</tr>
</table>
</>
簡而言之,為了按所選選項進行過濾,您必須:
這是工作代碼:
import "./styles.css";
import React, { useEffect, useState } from "react";
export default function App() {
const [data, getData] = useState([]);
const [selectedId, setSelectedId] = useState([]);
const URL = "https://jsonplaceholder.typicode.com/posts";
useEffect(() => {
fetchData();
}, []);
const fetchData = () => {
fetch(URL)
.then((res) => res.json())
.then((response) => {
console.log(response);
getData(response);
});
};
const handleSelectChange = (e) => {
console.log(e.target.value);
setSelectedId(e.target.value);
};
return (
<>
<select onChange={handleSelectChange} name="ids" id="ids">
<option value="1">Id 1</option>
<option value="2">Id 2</option>
<option value="3">Id 3</option>
<option value="4">Id 4</option>
</select>
<table>
<tr>
<th>User Id</th>
<th>Id</th>
<th>Title</th>
<th>Description</th>
</tr>
{data
.filter((value) => {
return Number(value.id) === Number(selectedId);
})
.map((item, i) => (
<tr key={i}>
<td>{item.userId}</td>
<td>{item.id}</td>
<td>{item.title}</td>
<td>{item.body}</td>
</tr>
))}
</table>
</>
);
}
工作沙箱: https://codesandbox.io/s/wonderful-feistel-qgrm0f?file=/src/App.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.