Реагировать JS: невозможно найти данные в таблице (таблице) по критериям поиска - PullRequest
0 голосов
/ 16 октября 2018

Я новичок в React Js и работаю над этим в течение последних 3 недель. На данный момент я могу получить данные из элементов формы, передать их через API через fetch и получить результаты, полученные вФормат таблицы / таблицы, но я пытаюсь реализовать критерии поиска в таблице. Если я ищу конкретное имя или текст, должна отображаться только эта строка, а не все строки, я использовал фрагмент кода, доступный в Интернете для Javascriptмодуль и внес изменения соответственно, но не были успешными.Ваши входные данные приветствуются.

  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 }));
      }

      searchFunction() {
        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");
        searchData = this.state.customerData.map((item, i) => {
          const ID = item.Field1;
          const Name = item.Field2;
          var compName = Name.toString();
          console.log('Name in search function:',Name);
          console.log('compName in search function:',compName);
          console.log('filter === Name',(filter === compName));
          if (filter === compName ){

            this.setState({respData:searchData});
          }

        });

} 


      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;

Вот правильный ответ:

myFunction() {
        var input, filter, table, tr, td, td1, 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");
        var innertext = table.getElementsByTagName("tr").innertext;
        console.log("innertext :",innertext);
        console.log('tr in searchFunction:',tr);
        for (i = 0; i < tr.length; i++) {
          td = tr[i].getElementsByTagName("td")[2];
          console.log('td in for before if:',td);
          if (td) {
            if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
              tr[i].style.display = "";
            } else {
              tr[i].style.display = "none";
            }
          }       

        }
    } 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...