You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中实现数据排序与筛选功能的技术咨询

Solution for Adding Sorting & Filtering to Student Table

Hey there! Let's tackle adding sorting and filtering to your student table. I'll walk you through creating a parent component that manages all the state and logic, plus updating your existing components to work with it. Here's the plan:

  • We'll have a parent StudentTable component that holds the student data, sorting preferences, and filter settings.
  • The filter dropdown will dynamically populate options based on which criteria you select (like showing all unique majors when you pick "Major" as the filter).
  • We'll add logic to sort the data and apply filters before passing it to the table rows.

Full Implementation Code

import React, { Component } from 'react';

class StudentRow extends Component {
  render() {
    const student = this.props.student;
    return (
      <tr>
        <td>{student.ID}</td>
        <td>{student.Name}</td>
        <td>{student.Age}</td>
        <td>{student.Major}</td>
        <td>{student.College}</td>
      </tr>
    );
  }
}

class FilterDropdown extends Component {
  render() {
    const { filterCriteria, filterValue, onFilterChange, filterOptions } = this.props;
    return (
      <div className="filter-section">
        <label>
          Filter by:
          <select 
            value={filterCriteria} 
            name="filterCriteria" 
            onChange={(e) => onFilterChange('filterCriteria', e.target.value)}
          >
            <option value="">-- Select Criteria --</option>
            <option value="ID">ID</option>
            <option value="Name">Name</option>
            <option value="Age">Age</option>
            <option value="Major">Major</option>
            <option value="College">College</option>
          </select>
        </label>
        
        {filterCriteria && (
          <label>
            Value:
            <select 
              value={filterValue} 
              name="filterValue" 
              onChange={(e) => onFilterChange('filterValue', e.target.value)}
            >
              <option value="">-- Select Value --</option>
              {filterOptions.map(option => (
                <option key={option} value={option}>{option}</option>
              ))}
            </select>
          </label>
        )}
      </div>
    );
  }
}

class SortDropdown extends Component {
  render() {
    const { sortCriteria, sortOrder, onSortChange } = this.props;
    return (
      <div className="sort-section">
        <label>
          Sort by:
          <select 
            value={sortCriteria} 
            name="sortCriteria" 
            onChange={(e) => onSortChange('sortCriteria', e.target.value)}
          >
            <option value="ID">ID</option>
            <option value="Name">Name</option>
            <option value="Age">Age</option>
            <option value="Major">Major</option>
            <option value="College">College</option>
          </select>
        </label>
        <label>
          Order:
          <select 
            value={sortOrder} 
            name="sortOrder" 
            onChange={(e) => onSortChange('sortOrder', e.target.value)}
          >
            <option value="ascending">Ascending</option>
            <option value="descending">Descending</option>
          </select>
        </label>
      </div>
    );
  }
}

class StudentTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      students: [
        // Sample data - replace with your actual data
        { ID: 1, Name: "Alice", Age: 20, Major: "Computer Science", College: "Engineering" },
        { ID: 2, Name: "Bob", Age: 21, Major: "Mechanical Engineering", College: "Engineering" },
        { ID: 3, Name: "Charlie", Age: 19, Major: "Computer Science", College: "Engineering" },
        { ID: 4, Name: "Diana", Age: 22, Major: "Physics", College: "Science" },
        { ID: 5, Name: "Eve", Age: 20, Major: "Physics", College: "Science" }
      ],
      sortCriteria: "ID",
      sortOrder: "ascending",
      filterCriteria: "",
      filterValue: ""
    };
    this.handleSortChange = this.handleSortChange.bind(this);
    this.handleFilterChange = this.handleFilterChange.bind(this);
  }

  handleSortChange(key, value) {
    this.setState({ [key]: value });
  }

  handleFilterChange(key, value) {
    this.setState({ [key]: value });
  }

  getFilteredStudents() {
    const { students, filterCriteria, filterValue } = this.state;
    if (!filterCriteria || !filterValue) return students;
    
    return students.filter(student => {
      const studentValue = student[filterCriteria].toString();
      return studentValue.toLowerCase() === filterValue.toLowerCase();
    });
  }

  getSortedStudents() {
    const filteredStudents = this.getFilteredStudents();
    const { sortCriteria, sortOrder } = this.state;
    
    return [...filteredStudents].sort((a, b) => {
      const valA = a[sortCriteria];
      const valB = b[sortCriteria];
      
      if (typeof valA === 'string') {
        return sortOrder === 'ascending' 
          ? valA.localeCompare(valB) 
          : valB.localeCompare(valA);
      } else {
        return sortOrder === 'ascending' 
          ? valA - valB 
          : valB - valA;
      }
    });
  }

  getFilterOptions() {
    const { students, filterCriteria } = this.state;
    if (!filterCriteria) return [];
    
    const uniqueValues = [...new Set(students.map(student => student[filterCriteria]))];
    return uniqueValues.sort();
  }

  render() {
    const sortedFilteredStudents = this.getSortedStudents();
    const filterOptions = this.getFilterOptions();
    
    return (
      <div>
        <div className="controls">
          <SortDropdown 
            sortCriteria={this.state.sortCriteria}
            sortOrder={this.state.sortOrder}
            onSortChange={this.handleSortChange}
          />
          <FilterDropdown 
            filterCriteria={this.state.filterCriteria}
            filterValue={this.state.filterValue}
            onFilterChange={this.handleFilterChange}
            filterOptions={filterOptions}
          />
        </div>
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>Name</th>
              <th>Age</th>
              <th>Major</th>
              <th>College</th>
            </tr>
          </thead>
          <tbody>
            {sortedFilteredStudents.map(student => (
              <StudentRow key={student.ID} student={student} />
            ))}
          </tbody>
        </table>
      </div>
    );
  }
}

export default StudentTable;

Key Features Explained

  • Parent State Management: The StudentTable component holds all the state for data, sorting, and filtering. This keeps the logic centralized and easy to maintain.
  • Dynamic Filter Options: The getFilterOptions method extracts unique values from the selected filter criteria (e.g., all unique majors when you pick "Major" as the filter). This ensures the dropdown always shows relevant options.
  • Sorting Logic: The getSortedStudents method sorts the filtered data. It handles both string and numeric values correctly, using localeCompare for strings and numeric comparison for numbers.
  • Filtering Logic: The getFilteredStudents method filters the data based on the selected criteria and value, with case-insensitive matching for strings.
  • Reusable Components: We split the sort and filter dropdowns into separate components to keep the code clean and reusable.

How to Use

  1. Replace the sample students array in StudentTable with your actual data.
  2. Style the controls and table as needed (add CSS classes for spacing and layout).
  3. Render the StudentTable component in your app.

This implementation gives you fully functional sorting and filtering with dynamic dropdown options for filters. Let me know if you need help adjusting any part of it!

内容的提问来源于stack exchange,提问作者Akash Rastogi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:03:39