[英]React - Slide fixed navbar up on scroll down and slide down on scroll up
tl; dr 向下滾動以獲取對我有用的解決方案!
如何在反應中在固定導航欄上實現上下滑動?
使用 refs 或使用 componentDidMount 生命周期鈎子的更好方法是什么?
hideNav = (navbar) => {
const hide = () => {
let lastScrollTop = 0;
const currentScrollTop = navbar.scrollTop;
// scroll down
if (currentScrollTop > lastScrollTop) {
navbar.classList.add('hidden');
} else {
// scroll up
navbar.classList.remove('hidden');
}
lastScrollTop = currentScrollTop;
};
window.addEventListener('scroll', hide);
};
...在渲染方法中進一步:
render() {
return <Navbar ref={this.hideNav} />
更新:
解決方案:
class Navbar extends React.Component {
state = {
auth: false,
slide: 0, // How much should the Navbar slide up or down
lastScrollY: 0, // Keep track of current position in state
};
componentWillMount() {
// When this component mounts, begin listening for scroll changes
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
// If this component is unmounted, stop listening
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll = () => {
const { lastScrollY } = this.state;
const currentScrollY = window.scrollY;
if (currentScrollY > lastScrollY) {
this.setState({ slide: '-48px' });
} else {
this.setState({ slide: '0px' });
}
this.setState({ lastScrollY: currentScrollY });
};
render() {
return (
<Navbar
style={{
transform: `translate(0, ${this.state.slide})`,
transition: 'transform 90ms linear',
}}
/>
);
}
}
我還沒有做任何優化,所以建議使用 requestAnimationFrame、setTimeout 或 customEvent 來限制事件。 就像這里。
您不應該使用 refs 作為注冊事件偵聽器或添加/刪除類的解決方案。 正如您所建議的,您應該使用組件生命周期掛鈎來開始(和停止)偵聽窗口上的滾動。
export default class App extends Component {
state = { hidden: false };
constructor(props) {
super(props);
// Bind the function to this component, so it has access to this.state
this.handleScroll = this.handleScroll.bind(this);
}
componentWillMount() {
// When this component mounts, begin listening for scroll changes
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
// If this component is unmounted, stop listening
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll(e) {
let lastScrollTop = 0;
const currentScrollTop = navbar.scrollTop;
// Set the state of hidden depending on scroll position
// We only change the state if it needs to be changed
if (!this.state.hidden && currentScrollTop > lastScrollTop) {
this.setState({ hidden: true });
} else if(this.state.hidden) {
this.setState({ hidden: false });
}
lastScrollTop = currentScrollTop;
}
render() {
// We pass a hidden prop to Navbar which can render className="hidden" if the prop is true
return (
<Navbar hidden={this.state.hidden} />
);
}
}
此外,查看您提供的滾動功能,它不起作用,因為lastScrollTop
將始終為 0。如果您正在尋找滾動解決方案,請查看此答案,因為它具有與固定導航欄類似的解決方案需要(除了,隱藏而不是顯示): 向下滾動后的粘性標題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.