Функция прокрутки не работает должным образом. Когда я прокручиваю вверх и вниз, классы не добавляются. Мне не удалось запустить функцию добавления класса onscroll. Итак, как я могу добавить функцию прокрутки класса. пожалуйста, предложите мне, как я могу добавить / удалить класс при прокрутке.
import React, { Component } from 'react';
import './App.css';
import About from './About';
import Contact from './Contact';
import {SectionsContainer, Section, Header, Footer} from 'react-fullpage';
class App extends Component {
state = {
isTop: true,
};
componentWillMount() {
var scrollpos = window.scrollY;
var header = document.querySelector("custom-section");
function add_class_on_scroll() {
header.classList.add("home-section--active");
}
function remove_class_on_scroll() {
header.classList.remove("home-section--active");
}
window.addEventListener('scroll', function(){
//Here you forgot to update the value
scrollpos = window.scrollY;
if (scrollpos > 10){
add_class_on_scroll();
}
else {
remove_class_on_scroll();
}
});
}
render() {
let options = {
sectionClassName: 'section',
anchors: ['sectionOne', 'sectionTwo', 'sectionThree'],
scrollBar: false,
navigation: false,
verticalAlign: false,
sectionPaddingTop: '0px',
sectionPaddingBottom: '0px',
arrowNavigation: false
};
return (
<div className = "App">
<SectionsContainer className = "container" {...options}>
<Section className = "custom-section home-section" verticalAlign = "true"><About/></Section>
<Section className = "custom-section home-section"><Contact /></Section>
</SectionsContainer>
</div>
);
}
}
export default App;





Вы должны поместить логику обработки прокрутки в жизненный цикл componentdidmount, так как после монтирования компонента у вас есть доступ к элементам DOM.
componentDidMount() {
var scrollpos = window.scrollY;
var header = document.querySelector("custom-section");
function add_class_on_scroll() {
header.classList.add("home-section--active");
}
function remove_class_on_scroll() {
header.classList.remove("home-section--active");
}
window.addEventListener('scroll', function(){
//Here you forgot to update the value
scrollpos = window.scrollY;
if (scrollpos > 10){
add_class_on_scroll();
}
else {
remove_class_on_scroll();
}
});
}