kkkkk31

91 阅读1分钟

如果你使用的是类组件而不是函数组件,并且希望在搜索框中输入关键字时过滤表格数据(如 username 列),你可以使用类组件的状态(state)和事件处理方法来实现。

以下是一个示例代码,展示了如何在类组件中实现搜索框过滤表格的功能:

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchKeyword: '',
      tableData: [
        { id: 1, username: 'user1' },
        { id: 2, username: 'user2' },
        { id: 3, username: 'user3' },
        // 表格数据...
      ]
    };
  }

  handleSearchChange = (event) => {
    this.setState({ searchKeyword: event.target.value });
  };

  render() {
    const { searchKeyword, tableData } = this.state;

    const filteredData = tableData.filter((data) =>
      data.username.toLowerCase().includes(searchKeyword.toLowerCase())
    );

    return (
      <div>
        <input type="text" value={searchKeyword} onChange={this.handleSearchChange} placeholder="Search by username" />
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>Username</th>
            </tr>
          </thead>
          <tbody>
            {filteredData.map((data) => (
              <tr key={data.id}>
                <td>{data.id}</td>
                <td>{data.username}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
}

在上述代码中,我们创建了一个继承自 React.Component 的类组件 MyComponent。我们在构造函数中初始化了两个状态变量:searchKeyword 用于存储搜索关键字,tableData 用于存储表格数据。我们还定义了 handleSearchChange 方法来处理搜索框值的变化,并通过调用 setState 方法更新 searchKeyword 状态变量的值。

render 方法中,我们使用 filter 方法根据搜索关键字过滤表格数据,并将过滤后的结果映射为表格行。

请根据你的具体需求和表格数据结构进行相应的调整。