对表格中的列进行排序不起作用

时间:2018-10-17 18:09:57

标签: javascript reactjs html-table columnsorting

我有一个显示搜索结果的表,我需要按字母顺序对其中的一列进行排序。当我单击列时,我希望对该列中的条目进行排序,但是我实现的方法不起作用。我还尝试使用Lodash的sortBy方法,但是仍然不能正确地对列进行排序。

import React, { PropTypes, Component } from 'react';
import {
  Panel,
  Button,
  Col,
  PageHeader,
  ControlLabel,
  FormControl,
  HelpBlock,
  FormGroup,
  Checkbox,
  Form,
  Radio,
  InputGroup,
  Glyphicon
} from 'react-bootstrap';

import FormControlFeedback from 'react-bootstrap/lib/FormControlFeedback';
import FormControlStatic from 'react-bootstrap/lib/FormControlStatic';
import InputGroupAddon from 'react-bootstrap/lib/InputGroupAddon';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      respData: []
    };

    this.handleSubmit = this.handleSubmit.bind(this
    this.myFunction = this.myFunction.bind(this);
    this.setArrow = this.setArrow.bind(this);
    this.onSort = this.onSort.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    const form = event.target;
    const data = new FormData(form);
    const arrayValue = [];
    var i = 0;
    console.log('Data from Form:', data);
    for (let name of data.keys()) {
      const input = form.elements[name];
      const parserName = input.dataset.parse;
      const parsedValue = data.get(name);
      console.log('name', name);
      console.log('parsedValue', parsedValue);
      if (typeof parsedValue == 'undefined' || parsedValue == null) {
        console.log('Not Undefined or Not Null');
        arrayValue[i] = '';
        data.set(name, arrayValue[i]);
      } else {
        data.set(name, parsedValue);
        arrayValue[i] = parsedValue;
      }

      i = i + 1;
    }

    var response_data = '';
    var response_jsonObj;
    var txt = '';
    var req = {
      RequestString: [
        {
          field1: arrayValue[0],
          field2: arrayValue[1],
          field3: arrayValue[2],
          field4: arrayValue[3],
          field5: arrayValue[4],
          field6: arrayValue[5],
          field7: arrayValue[6],
          field8: arrayValue[7],
          field9: arrayValue[8],
          field10: arrayValue[9],
          field11: arrayValue[10],
          field12: arrayValue[11],
          field13: arrayValue[12]
        }
      ]
    };

    console.log('req string :' + req);

    fetch('API_URL', {
      headers: {
        Accept: 'application/json, text/plain, application/xml,  */*',
        'Content-Type': 'application/json',
        'Access-Control-Allow-Headers': 'Content-Type'
      },
      method: 'POST',
      body: JSON.stringify(req)
    })
      .then(response => {
        if (response.status !== 200) {
          console.log('Problem in fetching');
          return;
        }
        //  this.setState({respData: response.data});

        response.text().then(data => {
          console.log('Data in Console', data);
          response_data = data;
          console.log('Response Data', response_data);
          response_jsonObj = JSON.parse(response_data);
          console.log('Response JSON Object', response_jsonObj);
        });
      })
      .catch(error => this.setState({ error }));
  }

  myFunction() {
    var input, filter, table, tr, td, i;
    input = document.getElementById('search');
    filter = input.value.toUpperCase();
    console.log('input in searchFunction:', input);
    console.log('filter in searchFunction:', filter);
    table = document.getElementById('Search-Table');
    console.log('table in searchFunction:', table);
    tr = table.getElementsByTagName('tr');
    console.log('tr in searchFunction:', tr);
    for (i = 0; i < tr.length; i++) {
      td = tr[i].getElementsByTagName('td')[0];
      console.log('td in for before if:', tr);
      if (td) {
        if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
          tr[i].style.display = '';
        } else {
          tr[i].style.display = 'none';
        }
      }
    }
  }

  onSort = (column) => (e) => {
        const direction = this.state.sort.column ? (this.state.sort.direction === 'asc' ? 'desc' : 'asc') : 'desc';
        const sortedData = this.state.respData.sort((a, b) => {
          if (column === 'Field1') {
            const nameA = a.Field1.toUpperCase(); // ignore upper and lowercase
            const nameB = b.Field1.toUpperCase(); // ignore upper and lowercase
            if (nameA < nameB) {
              return -1;
            }
            if (nameA > nameB) {
              return 1;
            }

            // names must be equal
            return 0;
          }
        });




        if (direction === 'desc') {
          sortedData.reverse();
        }

        this.setState({
          respData: sortedData,
          sort: {
              direction,
                column,
    }
        });
      };

      setArrow = (column,className) => {
        let current_className = className;

        if (this.state.sort.column === column) {
          current_className += this.state.sort.direction === 'asc' ? ' asc' : ' desc';
        }

        console.log(current_className);

        return current_className;
      };
  render() {
    return (
      <div id="SampleDiv">
        <form onSubmit={this.handleSubmit}>
          <table cellspacing="30">
            <tr>
              <td>
                <FormGroup>
                  <ControlLabel>Field 1</ControlLabel>
                  <FormControl
                    id="field1"
                    name="field1"
                    placeholder="Enter Text"
                  />
                </FormGroup>
              </td>
              <td>
                <FormGroup>
                  <ControlLabel>Field 2</ControlLabel>
                  <FormControl
                    id="field2"
                    name="field2"
                    type="text"
                    placeholder="Enter Text"
                  />
                </FormGroup>
              </td>
              <td>
                <FormGroup>
                  <ControlLabel>Field 3</ControlLabel>
                  <FormControl
                    id="field3"
                    name="field3"
                    type="text"
                    placeholder="Enter Text"
                  />
                </FormGroup>
              </td>
            </tr>
            <tr>
              <td>
                <FormGroup>
                  <ControlLabel>Field 4</ControlLabel>
                  <FormControl
                    id="field4"
                    name="field4"
                    type="text"
                    placeholder="Enter Text"
                  />
                </FormGroup>
              </td>
              <td>
                <FormGroup>
                  <ControlLabel>Field 5</ControlLabel>
                  <FormControl
                    id="field5"
                    name="field5"
                    type="text"
                    placeholder="Enter Text"
                  />
                </FormGroup>
              </td>
              <td>
                <FormGroup>
                  <ControlLabel>Field 6</ControlLabel>
                  <FormControl
                    id="field6"
                    name="field6"
                    type="text"
                    placeholder="Enter Text"
                  />
                </FormGroup>
              </td>
            </tr>
            <tr>
              <td>
                <FormGroup>
                  <ControlLabel>Field 7</ControlLabel>
                  <FormControl
                    id="field7"
                    name="field7"
                    type="text"
                    placeholder="Enter Text"
                  />
                </FormGroup>
              </td>
              <td>
                <FormGroup>
                  <ControlLabel>Field 8</ControlLabel>
                  <FormControl
                    id="field8"
                    name="field8"
                    type="text"
                    placeholder="Enter Text"
                  />
                </FormGroup>
              </td>
              <td>
                <FormGroup>
                  <ControlLabel>Field 9</ControlLabel>
                  <FormControl
                    id="field9"
                    name="field9"
                    type="text"
                    placeholder="Enter Text"
                  />
                </FormGroup>
              </td>
            </tr>
            <tr>
              <td>
                <FormGroup>
                  <ControlLabel>Field 10</ControlLabel>
                  <FormControl
                    id="field10"
                    name="field10"
                    type="text"
                    placeholder="Enter Text"
                  />
                </FormGroup>
              </td>
              <td>
                <FormGroup>
                  <ControlLabel>Field 11</ControlLabel>
                  <FormControl
                    id="field11"
                    name="field11"
                    type="text"
                    placeholder="Enter Text"
                  />
                </FormGroup>
              </td>
              <td>
                <FormGroup>
                  <ControlLabel>Field 12</ControlLabel>
                  <FormControl
                    id="field12"
                    name="field12"
                    type="text"
                    placeholder="Enter Text"
                  />
                </FormGroup>
              </td>
            </tr>
            <tr>
              <td>
                <FormGroup>
                  <ControlLabel>Field 13</ControlLabel>
                  <FormControl
                    id="field13"
                    name="field13"
                    type="text"
                    placeholder="Enter Text"
                  />
                </FormGroup>
              </td>
              <td />
              <td>
                <FormGroup>
                  <Button bsStyle="primary" type="submit">
                    Search{' '}
                  </Button>
                  {'  '}
                  <Button bsStyle="primary" type="reset">
                    Clear{' '}
                  </Button>
                </FormGroup>
              </td>
            </tr>
          </table>

          <div className="row ng-scope">
            <div className="col-lg-15">
              <Panel header={<span>Search Results</span>}>
                <div
                  id="dataTables-example_filter"
                  className="dataTables_filter"
                >
                  <label htmlFor={'search'}>
                    Search:
                    <input
                      type="search"
                      className="form-control input-sm"
                      placeholder=""
                      aria-controls="dataTables-example"
                      id="search"
                      onKeyUp={this.searchFunction}
                    />
                  </label>
                </div>

                <div className="table-responsive">
                  <table
                    id="Search-Table"
                    className="table table-striped table-bordered table-hover"
                  >
                    <thead>
                      <tr>
                        <th className="sorting_asc" onClick={this.onSort('Field 1','asc')} aria-sort="ascending"
                     aria-label="Field1 :activate to sort column descending"
                     aria-controls="dataTables-example" 
                     rowSpan="1"
                     colSpan="1"
                     tabIndex="0">Field 1
                     <span className={this.setArrow('Field 1')}></span>
                     </th>
                        <th>Field 2</th>
                        <th>Field 3</th>
                        <th>Field 4</th>
                        <th>Field 5</th>
                        <th>Field 6</th>
                        <th>Field 7</th>
                        <th>Field 8</th>
                        <th>Field 9</th>
                        <th>Field 10</th>
                      </tr>
                    </thead>

                    <tbody>
                      {this.state.respData.map((item, i) => {
                        return (
                          <tr key={i}>
                            <td> {item.Field1}</td>
                            <td> {item.Field2}</td>
                            <td> {item.Field3}</td>
                            <td> {item.Field4}</td>
                            <td> {item.Field5}</td>
                            <td> {item.Field6}</td>
                            <td> {item.Field7}</td>
                            <td> {item.Field8}</td>
                            <td> {item.Field9}</td>
                            <td> {item.Field10}</td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </Panel>
            </div>
          </div>
        </form>
      </div>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:0)

在您的代码中

     if (column === 'Field1') {
        const nameA = a.Field1.toUpperCase(); // ignore upper and lowercase
        const nameB = b.Field1.toUpperCase(); // ignore upper and lowercase
        if (nameA < nameB) {
          return -1;
        }
        if (nameA > nameB) {
          return 1;
        }

        // names must be equal
        return 0;
      }

您正在比较字符串,就好像它们是数字一样。这不是比较javascript中字符串的正确方法。

您应该使用

if (column === 'Field1') {
  return a.Field1.toUpperCase().localeCompare(b.Field1.toUpperCase());
}

您可以在MDN docs上了解有关localeCompare的更多信息