我正在使用 React,我想仅在用户在页面上向下滚动 150 像素后才显示标题。
所以当用户开始向下滚动时,我希望出现一个粘性标题。同样,当用户滚动到页面顶部时,粘性标题会消失。
<div className="container">
// display this on top of the page:
<JumbotronImage />
// display this when user starts to scroll, sticky on top of the page
<StickyHeader />
</div>
我试着用 window.addEventListener('scroll'... 来做,我也试过 https://github.com/fisshy/react-scroll 但还不能让它工作。有什么建议吗?
最佳答案
我认为您的代码如下所示。解决方案应该像这样。
export class App extends React.Component {
componentDidMount() {
ReactDOM.findDOMNode(this.stickyHeader).addEventListener('scroll', this.handleScroll.bind(this));
}
componentWillUnmount() {
ReactDOM.findDOMNode(this.stickyHeader).removeEventListener('scroll', this.handleScroll.bind(this));
}
handleScroll() {
// Add the logic here
}
render() {
const {props} = this;
return (
<div className="container">
// display this on top of the page:
<JumbotronImage />
// display this when user starts to scroll, sticky on top of the page
<StickyHeader ref = {ele => this.stickyHeader = ele} />
</div>
);
}
}
你可以引用这篇对我有用的文章,http://blog.sodhanalibrary.com/2016/07/detect-scroll-direction-using-reactjs.html#.Wo0hq0nTS-4在 handleScroll 中添加逻辑。
关于javascript - 如何仅在用户开始向下滚动后才显示标题? [ react ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48900019/