I am animating several React.js components based on their position in the viewport. If the component is in the viewport, animate the opacity to 1, if it's not in the viewport, animate its opacity to 0. I am using getBoundingClient()
's top
and bottom
properties to determine if the component is within the viewport.
ComponentA shows the pattern I followed for the other B, C, and D components. They each are listening for the window
scroll event.
Is this the "React" way to do this by each component having its having to add an event listener to the window
? Multiple scroll event listeners on the same window?
Or is there a better way by adding the scroll event listener to the window once at the Home
owner component? Then would the ownee child components still be able to know where they are in the DOM using the getBoundingClient()
?
Home = React.createClass({
render: function() {
<div>
<ComponentA />
<ComponentB />
<ComponentC />
<ComponentD />
</div>
};
});
ComponentA = React.createClass({
componentDidMount: function() {
window.addEventListener('scroll', this.handleScroll);
},
componentWillUnmount: function() {
window.removeEventListener('scroll', this.handleScroll);
},
handleScroll: function() {
var domElement = this.refs.domElement.getDOMNode();
this.inViewPort(domElement);
},
inViewPort: function(element) {
var elementBounds = element.getBoundingClientRect();
(elementBounds.top <= 769 && elementBounds.bottom >= 430) ? TweenMax.to(element, 1.5, { opacity: 1 }) : TweenMax.to(element, 1.5, { opacity: 0 });
},
render: function() {
return (/* html to render */);
}
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…