发布于 2016-06-30 14:43:06
与香草JS jsfiddle的反应方式;
别忘了删除EventListener。在此示例中,如果组件是必需的,则组件将呈现
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>;
}
}
发布于 2016-06-30 15:24:43
您可以使用诸如react-headroom之类的组件来为您完成繁重的工作。或者,您仍然可以在React中使用路点,在componentDidMount
lifecycle method中设置它,然后使用componentWillUnmount
将其删除。
发布于 2016-06-30 13:59:29
在componentDidMount
生命周期钩子中,执行与您给出的jQuery链接中相同的操作:
class Navbar extends React.component {
let delta = 5;
render() {
return (
<div ref=header></div>
);
}
componentDidMount() {
$(window).scroll(function(event){
var st = $(this).scrollTop();
if(Math.abs(this.state.lastScrollTop - st) <= delta)
return;
if (st > lastScrollTop){
// downscroll code
// $(this.refs.header).css('visibility','hidden').hover ()
this.setState({
navbarVisible: false
});
} else {
// upscroll code
$(this.refs.header).css('visibility','visible');
this.setState({
navbarVisible: true
});
}
lastScrollTop = st;
}.bind(this));
}
}
https://stackoverflow.com/questions/38114715
复制相似问题