在这个数字化时代,良好的用户界面设计对于提升用户体验至关重要。React 作为现代前端开发的流行框架,能够帮助我们创建出既美观又实用的应用界面。本文将带领你学习如何使用 React 打造一个包含左侧树形菜单和右侧表格的页面,实现数据的树形展示和表格的排序功能。
树形菜单的设计
1. 数据结构
首先,我们需要确定树形菜单的数据结构。通常,树形菜单的数据可以表示为一个嵌套的数组或对象。以下是一个简单的树形菜单数据的例子:
const menuData = [
{
id: 1,
title: ‘首页’,
children: [
{
id: 11,
title: ‘新闻’,
},
{
id: 12,
title: ‘公告’,
},
],
},
{
id: 2,
title: ‘关于我们’,
children: [
{
id: 21,
title: ‘公司简介’,
},
{
id: 22,
title: ‘团队介绍’,
},
],
},
];
2. 组件实现
接下来,我们将使用 React 创建一个
TreeMenu
组件,用于展示树形菜单。
import React, { useState } from ‘react’;
const TreeMenu = ({ data }) => {
const [expanded, setExpanded] = useState({});
const toggleItem = (id) => {
setExpanded({ …expanded, [id]: !expanded[id] });
};
return (
-
{data.map((item) => (
-
{item.title}
{item.children && ()}
))}
);
};
export default TreeMenu;
右侧表格的排序功能
1. 表格数据结构
表格的数据结构通常是一个扁平化的数组,每个元素代表一行数据。以下是一个简单的表格数据的例子:
const tableData = [
{
id: 1,
name: ‘张三’,
age: 25,
},
{
id: 2,
name: ‘李四’,
age: 30,
},
{
id: 3,
name: ‘王五’,
age: 28,
},
];
2. 表格组件实现
我们将创建一个
SortableTable
组件,用于展示表格数据,并实现排序功能。
import React, { useState } from ‘react’;
const SortableTable = ({ data, columns }) => {
const [sortConfig, setSortConfig] = useState({ key: null, direction: ‘ascending’ });
const sortedData = React.useMemo(() => {
let sortableData = […data];
if (sortConfig !== null) {
sortableData.sort((a, b) => {
if (a[sortConfig.key] < b[sortConfig.key]) {
return sortConfig.direction === 'ascending' ? -1 : 1;
}
if (a[sortConfig.key] > b[sortConfig.key]) {
return sortConfig.direction === ‘ascending’ ? 1 : -1;
}
return 0;
});
}
return sortableData;
}, [data, sortConfig]);
const requestSort = (key) => {
let direction = ‘ascending’;
if (sortConfig && sortConfig.key === key && sortConfig.direction === ‘ascending’) {
direction = ‘descending’;
}
setSortConfig({ key, direction });
};
return (
| requestSort(column.key)}> {column.title} {sortConfig && sortConfig.key === column.key ? ( {sortConfig.direction === ‘ascending’ ? ‘ 🔼’ : ‘ 🔽’} ) : null} |
|---|
| {row[column.key]} |
);
};
export default SortableTable;
组件整合
最后,我们将
TreeMenu
和
SortableTable
组件整合到一个页面中。
import React from ‘react’;
import TreeMenu from ‘./TreeMenu’;
import SortableTable from ‘./SortableTable’;
const App = () => {
const menuData = /* … */;
const tableData = /* … */;
const columns = [
{ key: ‘name’, title: ‘姓名’ },
{ key: ‘age’, title: ‘年龄’ },
];
return (
);
};
export default App;
通过以上步骤,我们成功地使用 React 打造了一个包含左侧树形菜单和右侧表格的页面。左侧菜单可以展示数据的树形结构,而右侧表格则支持数据的排序功能。这样的设计不仅美观,而且实用,能够提升用户体验。