假设我需要在用户滚动经过站点标题时向导航栏添加一个元素。如何在不使用 jQuery 的情况下在 React 中做这样的事情?
你可以做这样的事情:(这个函数是从我之前创建的我自己的react-sticky-dynamic-header复制的: https: //github.com/thinhvo0108/react-sticky-dynamic-header)
componentDidMount() {
var h1 = parseInt(this.refs.header.offsetHeight);
window.addEventListener('scroll', this._calcScroll.bind(this, h1));
}
componentWillUnmount() {
window.removeEventListener('scroll', this._calcScroll)
}
_calcScroll(h1) {
var _window = window;
var heightDiff = parseInt(h1);
var scrollPos = _window.scrollY;
if (scrollPos > heightDiff) {
// here this means user has scrolled past your header,
// you may rerender by setting State or do whatever
this.setState({
//stateKey: stateValue,
});
} else {
// here the user has scrolled back to header's territory,
// it's optional here for you to remove the element on navbar as stated in the question or not
this.setState({
//stateKey: stateValue,
});
}
}
render() {
return (
<div ref="header">YOUR HEADER HERE</div>
);
}
Run Code Online (Sandbox Code Playgroud)
为了在从导航栏中添加或删除元素时获得流畅的动画,您只需将其添加到元素的 CSS 样式中即可:
#your-element{
transition: opacity 0.3s ease-in;
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试安装我的库,看看它是否可以扩展您的需求:
https://www.npmjs.com/package/react-sticky-dynamic-header
如果有错误欢迎在这里留言,谢谢
归档时间: |
|
查看次数: |
4155 次 |
最近记录: |