Я хотел бы получить доступ ко всем элементам дом с определенным именем класса, но при реакции похоже, что это не работает, как в чистом javascript. Кажется, что не может найти элементы.
import React from 'react';
import {Route, Link} from 'react-router-dom';
import {Bootstrap, Grid, Row, Col, Button, Image, Modal, Popover} from 'react-bootstrap';
import Header from '../header/header.component';
import style from './information.style.scss';
import { Player } from 'video-react';
import YouTube from 'react-youtube';
class InformationJob extends React.Component {
constructor(props) {
super(props);
this.state = {
slideIndex: 1,
job: null,
};
this.showDivs = this.showDivs.bind(this);
}
plusDivs(n) {
this.setState({slideIndex: this.state.slideIndex + n});
this.showDivs(this.state.slideIndex);
}
showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
if (n > x.length) {this.setState({slideIndex :1})}
if (n < 1) {this.setState({slideIndex :x.length})}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[this.state.slideIndex-1].style.display = "block";
}
componentDidMount() {
this.showDivs(this.state.slideIndex);
}
_onReady(event) {
// access to player in all event handlers via event.target
event.target.pauseVideo();
}
render() {
const opts = {
height: '390',
width: '100%',
playerVars: { // https://developers.google.com/youtube/player_parameters
autoplay: 0
}
};
return (
<div className = {"wrapperDiv"}>
<div className = {"flexDivCol"}>
<div id = "header">
<Header size = "small"/>
</div>
<div>
<h3 className = {""} style = {{marginBottom: '20px'}}>Majoitus- ja ravitsemisala</h3>
<h4 className = {"primaryColor"}>Tarjoilija</h4>
</div>
<div id = "imageSection">
<div className = "w3-content w3-display-container">
<img className = "mySlides"
src = "https://thumbs.dreamstime.com/b/waitress-serving-food-to-visitors-young-european-couple-table-positive-plates-restaurant-48875722.jpg"/>
<img className = "mySlides"
src = "https://thumbs.dreamstime.com/b/waitress-serving-food-to-visitors-young-european-couple-table-positive-plates-restaurant-48875722.jpg"/>
<img className = "mySlides"
src = "https://thumbs.dreamstime.com/b/waitress-serving-food-to-visitors-young-european-couple-table-positive-plates-restaurant-48875722.jpg"/>
<img className = "mySlides"
src = "https://thumbs.dreamstime.com/b/waitress-serving-food-to-visitors-young-european-couple-table-positive-plates-restaurant-48875722.jpg"/>
<button className = "w3-button w3-black w3-display-left" onClick = {this.plusDivs(-1)}>❮</button>
<button className = "w3-button w3-black w3-display-right" onClick = {this.plusDivs(1)}>❯</button>
</div>
{/*<div className = {"screenSection"} style = {{backgroundImage: 'url(https://thumbs.dreamstime.com/b/waitress-serving-food-to-visitors-young-european-couple-table-positive-plates-restaurant-48875722.jpg)'}}></div>*/}
</div>
<div id = "jobDescription">
<p className = {"secondaryColor"}>Donec facilisis tortor ut augue lacinia, at viverra est semper. Sed sapien metus, scelerisque nec pharetra id, tempor a tortor. Pellentesque non dignissim neque. Ut porta viverra est, ut dignissim elit elementum ut. Nunc vel rhoncus nibh, ut tincidunt turpis. Integer ac enim pellentesque, adipiscing metus id, pharetra odio. Donec facilisis tortor ut augue lacinia, at viverra est semper. Sed sapien metus, scelerisque nec pharetra id, tempor a tortor. Pellentesque non dignissim neque. Ut porta viverra est, ut dignissim elit elementum ut. Nunc vel rhoncus nibh, ut tincidunt turpis. </p>
</div>
<div id = "videoSection">
<YouTube
videoId = "0cfVxK5YrGY"
opts = {opts}
onReady = {this._onReady}
/>
</div>
<div id = {"btnFilter"}>
<Link to='/traineeships'>
<Button className = {"primaryBtn"}>
Näytä harjoittelupaikat
</Button>
</Link>
</div>
</div>
</div>
);
}
}
export default InformationJob;
Я получил ошибку:
Uncaught TypeError: Cannot read property 'style' of undefined at InformationJob.showDivs (information-job.component.js:74) at InformationJob.plusDivs (information-job.component.js:58) at InformationJob.render (information-job.component.js:138)
Редактировать: Когда я консоль веду журнал var x = document.getElementsByClassName ("mySlides"); x показывает ноль.
у меня есть элементы с классом "mySlides"
Вы не используете setState для обновления состояния (обновляйте dom через состояние не напрямую)
я использую setState и все еще не работаю
@ChiragRavindra я обновил код и добавил setState



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Кнопка включения onClick (обе кнопки) постоянно вызывает функцию plusDivs, которая, в свою очередь, вызывает showDivs. Это должен быть onClick = {() => this.plusDivs(-1)}.
Это может произойти, если: 1) Никаких элементов с этим классом не найдено. 2) Если для доступа к элементам в массиве используется недопустимый индекс. Некоторые примечания: 1) Вы не используете
setStateдля обновления состояния 2) Возможно, вам будет лучше показывать / скрывать div на основе свойств или состояния и избегать ручного запроса элементов и работы с ними. 3) Даже если вы вручную установите невидимые элементы, при следующем рендеринге (при изменении состояния / реквизита) response отменит все ваши изменения.