Last active
February 15, 2019 21:48
-
-
Save tribou/d405436286807eeff669ad4d909331f5 to your computer and use it in GitHub Desktop.
Example React component that changes classes on scroll and supports passive event listeners where available
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react' | |
import css from './Header.css' | |
class Header extends Component { | |
componentDidMount () { | |
this._bindScroll() | |
} | |
componentWillUnmount () { | |
this._unbindScroll() | |
} | |
_bindScroll = () => { | |
// Use passive event listener if available | |
let supportsPassive = false | |
try { | |
const opts = Object.defineProperty({}, 'passive', { | |
get: () => { | |
supportsPassive = true | |
}, | |
}) | |
window.addEventListener('test', null, opts) | |
} | |
catch (e) {} // eslint-disable-line no-empty | |
window.addEventListener( | |
'scroll', | |
this._handleScroll, | |
supportsPassive ? { passive: true } : false | |
) | |
} | |
_unbindScroll = () => { | |
window.removeEventListener('scroll', this._handleScroll) | |
} | |
_handleScroll = () => { | |
// Ugly cross-browser compatibility | |
const top = document.documentElement.scrollTop | |
|| document.body.parentNode.scrollTop | |
|| document.body.scrollTop | |
// Test < 1 since Safari's rebound effect scrolls past the top | |
if (top < 1) { | |
const className = `${header.header}` | |
this._header.className = className | |
} | |
else { | |
const className = `${header.header} ${header.scrolled}` | |
this._header.className = className | |
} | |
} | |
render () { | |
return ( | |
<header | |
className={css.header} | |
ref={(ref) => { | |
this._header = ref | |
}} | |
> | |
</header> | |
) | |
} | |
} | |
export default Header |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Зачем все это - supportsPassive ? { passive: true } : false ? когда можно по дефолту всегда ставить этот параметр и браузер сам будет чекать поддерживается ли оно!