滚动功能无法正常工作。当我上下滚动时没有添加类。我未能触发添加类onscroll函数。因此,如何添加类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;
答案 0 :(得分:0)
您应该将滚动处理逻辑放在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();
}
});
}