我需要在反应中基本上重写这个codepen。 https://codepen.io/lili2311/pen/dJjuL
function resizeHeaderOnScroll() {
const distanceY = window.pageYOffset ||
document.documentElement.scrollTop,
shrinkOn = 200,
headerEl = document.getElementById('js-header');
if (distanceY > shrinkOn) {
headerEl.classList.add("smaller");
} else {
headerEl.classList.remove("smaller");
}
}
window.addEventListener('scroll', resizeHeaderOnScroll);
答案 0 :(得分:3)
一个简单的实现包括
答案 1 :(得分:0)
好的,这是我的尝试。不确定它是否能正常工作但它会让你大致了解如何在反应中构建它。
//Create a navbar component
class Navbar extends Component {
constructor() {
super();
//In the state you can keep track of the class you want to add to the element
this.state = {
class: "" //For now its empty or you can give it a default class.
}
}
//use the lifecycle methods to trigger the getWindowHeight method.
componentDidMount(){
() => {
window.addEventListener('scroll', this.getWindowHeight);
}
}
componentWillUnmount(){
() => {
window.removeEventListener('scroll', this.getWindowHeight);
}
}
//then create the method
getWindowHeight = () {
const distanceY = window.pageYOffset ||
document.documentElement.scrollTop
const shrinkOn = "200px";
//Now In the condition change the state to smaller so if the condition is true it will change to smaller otherwise to default state
if (distanceY > shrinkOn) {
this.setState({
class: "smaller"
})
}
}
render() {
return (
//Now in the element you can add the state to the class as well as add event to the onScroll
<navbar className={this.state.class} >
</navbar >
)
}