【发布时间】:2021-04-01 01:27:19
【问题描述】:
在我的应用程序中,我想创建一个可重用的数据表组件。数据来自后端,我需要对这些数据进行排序。数据是数字和字符串。现在我想以升序和降序按钮显示数据。这是我的数据表代码:
//Table Component
const Table = ({ headers, data }) => {
return (
<table>
<thead>
<tr>
{headers.map(head => (
<th>{head}</th>
))}
</tr>
</thead>
<tbody>
{data.map(row => (
<tr>
{headers.map(head => (
<td>{row[head]}</td>
))}
</tr>
))}
</tbody>
</table>
//app.js
export default function App() {
const headers = ['userId', 'id', 'title', 'body'];
useEffect(() => {
const getPosts = async () => {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
setData(data);
};
getPosts();
}, []);
const filteredData = slice.filter(
post => post.title.toLowerCase().includes(keyword) || post.body.toLowerCase().includes(keyword),
);
const onInputChange = e => {
e.preventDefault();
setKeyword(e.target.value.toLowerCase());
};
return (
<div>
div className="table-search-form">
<input
className="form-control"
type="text"
placeholder="Search..."
onChange={onInputChange}
/>
</div>
<DataTable headers={headers} posts={filteredData} />
</div>
);
}
【问题讨论】:
标签: reactjs api sorting react-hooks