0

Изучаю React читаю доки, туториалы. Решил попробовать перевести JSP в отдельный фронт на React. Начал с малого, с одного компонента, это автопоиск, принцип, вводим слово и он выдает варианты.

Почти все получилось, только никак не могу справится с тем, как мне листать список по клавишам вверх-вниз, я не могу понять, как передать свойство выше и сказать, чтобы тот или иной li изменил класс на selected.

Я пробовал через map(item, key), но как мне в этот item передать свойство например?

Вот мой код, еше бы хотел попросить посмотреть, сделал ли я его чистым, или есть замечания, чтобы их сразу разобрать, буду благодарен :)

import React, { Component } from "react";
import "./App.css";

class ProductRow extends React.Component {
  constructor(props) {
    super(props);
    this.handlerrOnMouseOver = this.handlerrOnMouseOver.bind(this);
    this.handlerrOnMouseOut = this.handlerrOnMouseOut.bind(this);
    this.handlerrOnMouseDown = this.handlerrOnMouseDown.bind(this);
    this.state = {
      class: ""
    };
  }

  handlerrOnMouseOver() {
    this.setState({
      class: "selected"
    });
  }

  handlerrOnMouseOut() {
    this.setState({
      class: ""
    });
  }

  handlerrOnMouseDown() {
    this.props.callback(this.props.product.station);
  }

  render() {
    const product = this.props.product;
    return (
      <li
        className={this.state.class}
        onMouseOver={this.handlerrOnMouseOver}
        onMouseOut={this.handlerrOnMouseOut}
      >
        <a href="javascript:void(0);" onMouseDown={this.handlerrOnMouseDown}>
          {product.station}
        </a>
      </li>
    );
  }
}

class ProductTable extends React.Component {
  render() {
    const filterText = this.props.filterText;
    const rows = [];
    if (filterText !== "") {
      this.props.products.map((product, key) => {
        if (
          product.station.toLowerCase().indexOf(filterText.toLowerCase()) ===
            -1 ||
          rows.length === 20
        ) {
          return;
        } else {
          rows.push(
            <ProductRow
              product={product}
              key={key}
              callback={this.props.callback}
            />
          );
        }
      });
    }

    var style = {
      width: "100%",
      fontSize: 14
    };

    if (rows.length > 0) {
      return (
        <div className="sf_suggestion">
          <ul tabIndex="-1" style={style}>
            {rows}
          </ul>
        </div>
      );
    } else {
      return <div />;
    }
  }
}

class SearchBar extends React.Component {
  constructor(props) {
    super(props);
    this.handlerFilterTextChange = this.handlerFilterTextChange.bind(this);
    this.handlerOnKeyUp = this.handlerOnKeyUp.bind(this);
    this.handlerOnBlur = this.handlerOnBlur.bind(this);
    this.changeValue = this.changeValue.bind(this);
    this.handlerOnFocus = this.handlerOnFocus.bind(this);
    this.state = {
      visible: true,
      filterText: "",
      key: ""
    };
  }

  handlerFilterTextChange(e) {
    e.preventDefault();
    this.setState({ filterText: e.target.value });
  }

  handlerOnKeyUp() {
    var key = window.event.keyCode;
    if (key === 38 || key === 40 || key === 13) {
      this.setState({ key: key });
    }
    if (key === 27) {
      this.setState({ visible: false });
    }
  }

  changeValue(e) {
    this.setState({ filterText: e });
    this.handlerOnBlur();
  }

  handlerOnBlur() {
    this.setState({ visible: false });
    this.setState({ key: "" });
  }

  handlerOnFocus() {
    if (!this.state.visible) {
      this.setState({ visible: true });
    }
  }

  render() {
    return (
      <p className="inp">
        <label>
          <input
            type="text"
            placeholder="&nbsp;"
            value={this.state.filterText}
            onChange={this.handlerFilterTextChange}
            onFocus={this.handlerOnFocus}
            onKeyUp={this.handlerOnKeyUp}
            onBlur={this.handlerOnBlur}
          />
          <span className="label">{this.props.name}</span>
          <span className="border" />
          {this.state.visible && (
            <ProductTable
              products={this.props.products}
              filterText={this.state.filterText}
              keyUp={this.state.key}
              callback={this.changeValue}
            />
          )}
        </label>
      </p>
    );
  }
}

class App extends Component {
  render() {
    return (
      <table>
        <tbody>
          <td>
            <SearchBar products={this.props.products} name={"Имя"} />
          </td>
        </tbody>
      </table>
    );
  }
}

export default App;

1 ответ 1

2

Отрефакторенный вариант с заметками:

import React, { Component } from "react";
import "./App.css";

class ProductRow extends React.Component {
  constructor(props) {
    super(props);
    this.handlerrOnMouseOver = this.handlerrOnMouseOver.bind(this);
    this.handlerrOnMouseOut = this.handlerrOnMouseOut.bind(this);
    this.handlerrOnMouseDown = this.handlerrOnMouseDown.bind(this);
    this.state = {
      className: "" // class очень плохое название, потому что является зарезервированным названием ЯП. Используйте className или подобное
    };
  }

  handlerrOnMouseOver() {
    this.setState({
      className: "selected"
    });
  }

  handlerrOnMouseOut() {
    this.setState({
      className: ""
    });
  }

  handlerrOnMouseDown() {
    /**
     * нужно всегда проверять пришли ли пропсы, потому что если нет, то вывалит ошибку что не может получить callback из undefined
     * деструктуризация делает код более читабельным
     */
    const { callback, product } = this.props;

    callback && callback(product && product.station);
  }

  render() {
    // бессмысленная запись, которая ничего не дает
    // const product = this.props.product;

    /**
     * используйте деструктуризацию
     */
    const { product } = this.props;
    const { className } = this.state;

    return (
      <li
        className={className}
        onMouseOver={this.handlerrOnMouseOver}
        onMouseOut={this.handlerrOnMouseOut}
      >
        <a href="javascript:void(0);" onMouseDown={this.handlerrOnMouseDown}>
          {product.station}
        </a>
      </li>
    );
  }
}

class ProductTable extends React.Component {
  render() {
    /**
     * используйте деструктуризацию
     */
    const { filterText, products, callback } = this.props;
    // бессмысленная запись, которая ничего не дает
    // const filterText = this.props.filterText;

    // лучше присваивать CSS-класс, чем инлайновый стиль
    var style = {
      width: "100%",
      fontSize: 14
    };

    /**
     * судя по коду, нет обязательной привязки к пустой строке, поэтому простой проверки будет достаточно
     */
    return (
      filterText && (
        <div className="sf_suggestion">
          <ul tabIndex="-1" style={style}>
            {products
              .filter(
                (product, i) =>
                  product.station
                    .toLowerCase()
                    // includes() более новый и удобный метод
                    .includes(filterText.toLowerCase()) && (
                    <ProductRow product={product} key={i} callback={callback} />
                  )
              )
              .slice(0, 20)}
          </ul>
        </div>
      )
    );
  }
}

class SearchBar extends React.Component {
  constructor(props) {
    super(props);
    this.handlerFilterTextChange = this.handlerFilterTextChange.bind(this);
    this.handlerOnKeyUp = this.handlerOnKeyUp.bind(this);
    this.handlerOnBlur = this.handlerOnBlur.bind(this);
    this.changeValue = this.changeValue.bind(this);
    this.handlerOnFocus = this.handlerOnFocus.bind(this);
    this.state = {
      visible: true,
      filterText: "",
      key: ""
    };
  }

  handlerFilterTextChange(e) {
    e.preventDefault();
    this.setState({ filterText: e.target.value });
  }

  handlerOnKeyUp() {
    var key = window.event.keyCode;
    if (key === 38 || key === 40 || key === 13) {
      this.setState({ key: key });
    }
    if (key === 27) {
      this.setState({ visible: false });
    }
  }

  changeValue(e) {
    this.setState({ filterText: e });
    this.handlerOnBlur();
  }

  handlerOnBlur() {
    // обновляйте весь стейт за раз
    this.setState({
      visible: false,
      key: ""
    });
  }

  handlerOnFocus() {
    if (!this.state.visible) {
      this.setState({ visible: true });
    }
  }

  render() {
    return (
      <p className="inp">
        <label>
          <input
            type="text"
            placeholder="&nbsp;"
            value={this.state.filterText}
            onChange={this.handlerFilterTextChange}
            onFocus={this.handlerOnFocus}
            onKeyUp={this.handlerOnKeyUp}
            onBlur={this.handlerOnBlur}
          />
          <span className="label">{this.props.name}</span>
          <span className="border" />
          {this.state.visible && (
            <ProductTable
              products={this.props.products}
              filterText={this.state.filterText}
              keyUp={this.state.key}
              callback={this.changeValue}
            />
          )}
        </label>
      </p>
    );
  }
}

class App extends Component {
  render() {
    return (
      <table>
        <tbody>
          <td>
            <SearchBar products={this.props.products} name={"Имя"} />
          </td>
        </tbody>
      </table>
    );
  }
}

export default App;

Мой вариант (не уверен почему изменение цвета при наведении мышью хендлится в JS а не в CSS, но не менял, и сделал в коде):

const mockData = [
  {
    station: "first",
  },
  {
    station: "second",
  },
  {
    station: "third",
  },
]

class Search extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      filteredItems: props.items || [],
      selectedItem: null
    };
  }

  onFilterTextChanged = (event) => {
    event.preventDefault();
    const { items } = this.props;
    this.setState({
      filteredItems: items.filter(el => el.station.toLowerCase().includes(event.target.value.toLowerCase()))
    });
  }

  onKeyUp = ({ keyCode }) => {
    const { selectedItem, filteredItems } = this.state;
    if (keyCode === 40) {
      if (selectedItem === null) {
        this.setState({ selectedItem: 0 });
      } else if (selectedItem < filteredItems.length - 1) {
        this.setState({ selectedItem: selectedItem + 1 });
      }
    }
    if (keyCode === 38) {
      if (selectedItem > 0) {
        this.setState({ selectedItem: selectedItem - 1 });
      }
    }
  }

  onMouseOver = (index) => {
    this.setState({
      selectedItem: index
    });
  }

  onMouseOut = () => {
    this.setState({
      selectedItem: null
    });
  }

  render() {
    const { selectedItem, filteredItems } = this.state;

    return (
      <div>
        <input
          type="text"
          placeholder="Enter station to filter..."
          onChange={this.onFilterTextChanged}
          onKeyUp={this.onKeyUp}
        />
        <table>
          <tbody>
            {
              filteredItems.map((item, i) => (
                <tr
                  key={`item-${i}`}
                  className={selectedItem === i? `selected` : ``}
                  onMouseOver={() => this.onMouseOver(i)}
                  onMouseOut={() => this.onMouseOut()}
                >
                  <td>{item.station}</td>
                </tr>
              ))
            }
          </tbody>
        </table>
      </div>
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <Search items={mockData} />
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
.selected {
  background-color: lavender;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

6
  • классно, спасибо большое, буду знать нюансы. А можно еще вас попросить подсказать, как по клавише вниз вверх можно менять состояние класса стиля? Чтобы присваивался selected? я перебираю rows.map((item, key) => ... получаю item, но дальше не могу понять, как мне попасть в компонент дочерний, чтобы у li сделать className="selected" 19 фев 2019 в 10:43
  • До конца дня занят, попозже гляну 19 фев 2019 в 11:11
  • Это вообще не к спеху, думал, что вдруг проблема на лету решается, сам уже второй день ломаю голову:) 19 фев 2019 в 11:37
  • @Владислав добавил свой вариант решения Вашей задачи. Написал с нуля, потому что так проще)) 19 фев 2019 в 17:07
  • 1
    А я пытался сделать так, в state родителя создавал индекс, далее прокидывал выше номер клавиши, если это 40, я увеличивал индекс, если 38 уменьшал, далее через map пытался передать этот индекс, и вот как раз ему поменять класс, у меня и не выходило, не мог понять как прокинуть. :) Теперь дело пойдет) 19 фев 2019 в 17:26

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.