Skip to content

Sortable 数据表

中等 约 30 分钟

你将构建什么

数据表 displaying 列表的 用户使用列 for name, age, and role. 点击列 请求头排序表 通过那个列, 使用切换之间 ascending and descending.

学习目标

  • 渲染 tabular 数据使用 .映射()
  • Implement 列排序 logic
  • Use useMemo 到缓存排序数据
  • Handle 排序方向切换

前置要求

  • 列表渲染使用映射
  • useState and useMemo
  • 数组排序方法

步骤

  1. 1

    设置数据 and 排序状态

    创建数组的 用户对象 and 状态 for 排序列 and 方向.

    代码
    const [sortKey, setSortKey] = useState("name");
    const [sortDir, setSortDir] = useState("asc");
    
    const users = [
      { name: "Alice", age: 30, role: "Admin" },
      { name: "Bob", age: 25, role: "User" },
      { name: "Charlie", age: 35, role: "Editor" },
    ];

    预期结果

    数据 and 排序状态是 ready.

  2. 2

    Memoize 排序数据

    Use useMemo 到排序用户数组 based on sortKey and sortDir. 这个 avoids re-排序 on 每个渲染.

    代码
    const sortedUsers = useMemo(() => {
      return [...users].sort((a, b) => {
        const val = a[sortKey] < b[sortKey] ? -1 : a[sortKey] > b[sortKey] ? 1 : 0;
        return sortDir === "asc" ? val : -val;
      });
    }, [users, sortKey, sortDir]);

    预期结果

    数据是 排序 and cached. 更改排序状态 re-排序.

  3. 3

    渲染表 使用 sortable 请求头

    渲染表 使用 clickable 请求头那个更新 sortKey and 切换 sortDir.

    代码
    <table>
      <thead>
        <tr>
          <th onClick={() => handleSort("name")}>Name</th>
          <th onClick={() => handleSort("age")}>Age</th>
          <th onClick={() => handleSort("role")}>Role</th>
        </tr>
      </thead>
      <tbody>
        {sortedUsers.map(u => (
          <tr key={u.name}>
            <td>{u.name}</td><td>{u.age}</td><td>{u.role}</td>
          </tr>
        ))}
      </tbody>
    </table>

    预期结果

    点击请求头排序表 通过那个列.

  4. 4

    添加状态管理与事件处理

    使用 useState 管理组件状态,为交互元素添加 onClick/onChange 事件处理。状态是 React 组件的核心,事件处理让组件响应用户操作。

    代码
    import { useState } from "react";
    
    export function MyComponent() {
      const [count, setCount] = useState(0);
      const [text, setText] = useState("");
    
      return (
        <div>
          <button onClick={() => setCount(c => c + 1)}>
            Count: {count}
          </button>
          <input
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
        </div>
      );
    }

    预期结果

    点击按钮计数递增;输入框内容随键入实时更新。

  5. 5

    添加 Props 验证与组件拆分

    为组件定义 Props 接口(TypeScript)或 propTypes,将大组件拆分为更小的子组件。类型安全的 Props 让组件接口清晰、可复用。

    代码
    interface ChildProps {
      label: string;
      value: number;
      onChange: (v: number) => void;
    }
    
    function Child({ label, value, onChange }: ChildProps) {
      return (
        <label>
          {label}
          <input
            type="number"
            value={value}
            onChange={(e) => onChange(Number(e.target.value))}
          />
        </label>
      );
    }

    预期结果

    子组件接收类型安全的 Props;父组件可复用子组件渲染多个字段。

自己动手试试

你学到了什么

你学习到 渲染 tabular 数据, implement 排序使用 useMemo for 性能, and handle 用户 interactions on 表请求头. 这个是 常见模式 in admin dashboards and 数据-heavy apps.

相关资源

相关课程

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题