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

React实现点击表格Name表头按名称字母排序的方法

How to Add Name Sorting to Your React Table

Got it, let's get your table sorting by name when clicking the header. Here's a straightforward way to implement this with your existing code:

Step 1: Add Sort State and Handler to the Parent Component (Stuff.js)

First, we need to track the current sort direction (ascending/descending) in the parent's state, and create a function to sort the items array.

  • Add a sortDirection state variable (defaulting to 'asc' for ascending).
  • Create the handleNameSort method that sorts the items case-insensitively by name, and toggles the sort direction each time it's called.

Here's the modified Stuff.js code:

import React, { Component } from 'react'; 
import './App.css'; 
import Tab from './Table'; 
import Form from './Form'; 

class Stuff extends Component { 
  constructor() { 
    super(); 
    this.state = { 
      name: '', 
      origin: '', 
      destination: '', 
      seats: '', 
      items: [],
      sortDirection: 'asc' // Track sort direction
    } 
  }; 

  handleFormSubmit = (e) => { 
    e.preventDefault(); 
    let items = [...this.state.items]; 
    items.push({ 
      name: this.state.name, 
      origin: this.state.origin, 
      destination: this.state.destination, 
      seats: this.state.seats 
    }); 
    this.setState({ items, name: '', origin: '', destination: '', seats: '' }); 
  }; 

  handleInputChange = (e) => { 
    let input = e.target; 
    let name = e.target.name; 
    let value = input.value; 
    this.setState({ [name]: value }) 
  }; 

  // Sort handler for name column
  handleNameSort = () => {
    const { items, sortDirection } = this.state;
    // Create a copy of items to avoid mutating state directly
    const sortedItems = [...items].sort((a, b) => {
      // Convert names to lowercase for case-insensitive sorting
      const nameA = a.name.toLowerCase();
      const nameB = b.name.toLowerCase();
      
      if (nameA < nameB) {
        return sortDirection === 'asc' ? -1 : 1;
      }
      if (nameA > nameB) {
        return sortDirection === 'asc' ? 1 : -1;
      }
      return 0; // Names are equal
    });

    // Update state with sorted items and toggle direction
    this.setState({
      items: sortedItems,
      sortDirection: sortDirection === 'asc' ? 'desc' : 'asc'
    });
  };

  render() { 
    return ( 
      <div className="App"> 
        <Form 
          handleFormSubmit={ this.handleFormSubmit } 
          handleInputChange={ this.handleInputChange } 
          newName={ this.state.name } 
          newOrigin={ this.state.origin } 
          newDestination={ this.state.destination } 
          newSeats={ this.state.seats } 
        /> 
        {/* Pass sort handler and direction to Table component */}
        <Tab 
          items={ this.state.items } 
          onNameSort={ this.handleNameSort } 
          sortDirection={ this.state.sortDirection } 
        /> 
      </div> 
    ); 
  } 
} 

export default Stuff;

Step 2: Make the Name Header Interactive (Table.js)

Now, we need to make the Name column header clickable, trigger the sort handler when clicked, and show an indicator for the current sort direction.

  • Add an onClick event to the Name <th> that calls the onNameSort prop from the parent.
  • Style the header to have a pointer cursor so users know it's clickable.
  • Add an arrow (↑/↓) to show if we're sorting ascending or descending.

Modified Table.js code:

import React, { Component } from 'react'; 
import { Table } from 'reactstrap'; 

class Tab extends React.Component { 
  render() { 
    const items = this.props.items; 
    return ( 
      <Table striped> 
        <thead> 
          <tr> 
            {/* Clickable Name header with sort indicator */}
            <th 
              onClick={this.props.onNameSort} 
              style={{ cursor: 'pointer' }}
            >
              Name {this.props.sortDirection === 'asc' ? '↑' : '↓'}
            </th> 
            <th>Origin</th> 
            <th>Destination</th> 
            <th>Seats</th> 
          </tr> 
        </thead> 
        <tbody> 
          {items.map(item => { 
            return ( 
              <tr> 
                <td>{item.name}</td> 
                <td>{item.origin}</td> 
                <td>{item.destination}</td> 
                <td>{item.seats}</td> 
              </tr> 
            ); 
          })} 
        </tbody> 
      </Table> 
    ); 
  } 
} 

export default Tab;

How It Works

  • When you click the Name header, it triggers the handleNameSort function in the parent component.
  • This function creates a copy of the items array, sorts it by name (case-insensitively), and updates the state with the sorted array.
  • The sort direction toggles between ascending ('asc') and descending ('desc') each time you click, so users can switch between the two orderings.
  • The arrow next to Name shows the current sort direction, making it clear to users how the data is ordered.

内容的提问来源于stack exchange,提问作者Anand Trivedi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:53:59