@75db77

Как бы выглядел этот код без хуков (hooks) и с компонентами класса, а не с функциональными компонентами?

Здравствуйте!
Как бы выглядел предложенный код но без хуков(hooks) и с классовыми компонентами а не функциональными? Я просто изучал React по учебнику где все уроки были построены на классах и обычных this.setState, без хуков, и сейчас путаюсь, потому-что думаю так как учили, а тут уже что-то новое и каша какая-то получается у меня. В перспективе конечно хочу и хуки виучить, и компонеты на основе функций, но пока не хочу смешивать что б лучше разобраться.

React.js:

function Slider({ items }) {
  const [ active, setActive ] = React.useState(0);
  const { length, [active]: slide } = items;

  const next = e => setActive((active + +e.target.dataset.step + length) % length);
  const goTo = e => setActive(+e.target.dataset.index);

    React.useEffect(() => {
    const timeout = setTimeout(() => setActive((active + 1 + length) % length), 5000);

    return () => clearTimeout(timeout);
  }, [active, length]);

  return (
    <div>
      <div className="slideshow-container">
        <div className="mySlides fade">
          <div className="numbertext">{active + 1} / {length}</div>
          <img src={slide.img} />
          <div className="text">{slide.title}</div>
        </div>
        <a className="prev" onClick={next} data-step={-1}>&#10094;</a>
        <a className="next" onClick={next} data-step={+1}>&#10095;</a>
      </div>
      <div className="dots">
        {items.map((n, i) => (
          <span
            key={n.id}
            className={`dot ${i === active ? 'active' : ''}`}
            onClick={goTo}
            data-index={i}
          ></span>
        ))}
      </div>
    </div>
  );
}

const items = [
  { title: 'One', img: 'https://upload.wikimedia.org/wikipedia/commons/1/1f/Purity_of_nature.jpg' },
  { title: 'Two', img: 'https://mairie-balma.fr/wp-content/uploads/2016/06/Lhers.jpg' },
  { title: 'Three', img: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRt-b1iBqHQ_emkm1wFmkM7KQskzIqg7YQPZWW85Sa7k2nNLwgjMw' },
].map((n, i) => ({ ...n, id: i + 1 }));

ReactDOM.render(<Slider items={items} />, document.getElementById('app'));


html:
<div id="app"></div>

css:
.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
}


.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}


.prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
}


.text {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
  box-sizing: border-box;
}


.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}


.dots {
  display: flex;
  justify-content: center;
}

.dot {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active, .dot:hover {
  background-color: #717171;
}

.mySlides img {
  width: 100%;
}
  • Вопрос задан
  • 145 просмотров
Решения вопроса 1
pterodaktil
@pterodaktil
js developer
class Slider extends Component {
  state = {
    active: 0
  };

  componentDidMount() {
    const { items } = this.props;

    this.timeout = setTimeout(
      () => this.updateActive(this.state.active, 1, items.length),
      5000
    );
  }
  componentDidUpdate(prevProps, prevState) {
    const { items } = this.props;
    const { active } = this.state;

    if (
      prevState.active !== active ||
      prevProps.items.length !== items.length
    ) {
      clearTimeout(this.timeout);
      this.timeout = setTimeout(
        () => this.updateActive(active, 1, items.length),
        5000
      );
    }
  }
  componentWillUnmount() {
    clearInterval(this.timeout);
  }

  updateActive = (active, step, length) => {
    this.setState({
      active: step ? (active + step + length) % length : active
    });
  };
  next = e =>
    this.setState({
      active: this.updateActive(
        this.state.active,
        +e.target.dataset.step,
        this.props.items.length
      )
    });
  goTo = e => this.updateActive(+e.target.dataset.index);

  render() {
    const { active } = this.state;
    const { items } = this.props;

    const { length, [active]: slide } = items;

    return (
      <div>
        <div className="slideshow-container">
          <div className="mySlides fade">
            <div className="numbertext">
              {active + 1} / {length}
            </div>
            <img src={slide.img} />
            <div className="text">{slide.title}</div>
          </div>
          <a className="prev" onClick={this.next} data-step={-1}>
            &#10094;
          </a>
          <a className="next" onClick={this.next} data-step={+1}>
            &#10095;
          </a>
        </div>
        <div className="dots">
          {items.map((n, i) => (
            <span
              key={n.id}
              className={`dot ${i === active ? "active" : ""}`}
              onClick={this.goTo}
              data-index={i}
            />
          ))}
        </div>
      </div>
    );
  }
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
26 апр. 2024, в 07:47
2000 руб./за проект
26 апр. 2024, в 06:46
1000 руб./в час
26 апр. 2024, в 05:31
1000 руб./за проект