如何在滚动时显示 React 组件
我为固定导航创建了一个 React 组件,我希望将其保持隐藏状态,直到我滚动经过页面上的某个点,然后滑入视图.Medium 的标头与我所描述的类似.
I've created a React component for a fixed nav that I would like to remain hidden, until I scroll past a certain point on the page, then slides into view. Medium has a header similar to what I'm describing.
这是jQuery,带有 scrollmagic 或航路点,但是否有一种惯用的方法可以使用 React 和 vanilla JS 来实现这一点?
This is a relatively trivial task in jQuery, with scrollmagic or waypoints but is there an idiomatic way of accomplishing this with React and vanilla JS?
React Way with vanilla JS jsfiddle;
React Way with vanilla JS jsfiddle;
不要忘记删除 EventListener.在此示例中,组件将在必要时呈现
don't forget to remove EventListener. In this example component will render if only it is neccessary
class TopBar extends React.Component {
state = { isHide: false };
hideBar = () => {
const { isHide } = this.state
window.scrollY > this.prev ?
!isHide && this.setState({ isHide: true })
:
isHide && this.setState({ isHide: false });
this.prev = window.scrollY;
}
componentDidMount(){
window.addEventListener('scroll', this.hideBar);
}
componentWillUnmount(){
window.removeEventListener('scroll', this.hideBar);
}
render(){
const classHide = this.state.isHide ? 'hide' : '';
return <div className={`topbar ${classHide}`}>topbar</div>;
}
}