我是 React.js 的初学者并且有一个问题。我试图在滚动上显示图标,每个图标都有一点时间延迟。类似的东西Example template .在这个 Bootstrap 模板中,您可以看到我们何时滚动显示图标(每个图标都有一点时间延迟)。它可能与 jquery 滚动显示模块。但我不知道如何使用 React.js 实现这一点。无论如何只使用 javascript 在 react.js 中做到这一点?这是我的 react 功能组件代码。
import React from 'react';
function Howitworks() {
return (
<div className="my-5">
<div className="container text-center" id="contactContainer">
<div className="row">
<div className="col-lg-12 mx-auto">
<h2 className="text-center">How It Works</h2>
<hr className="my-4 thick-hr-2" />
</div>
</div>
</div>
<div className="container text-center">
<div className="row">
<div className="col-md-6 col-lg-4">
<div className="service-box mt-5 mx-auto">
<span className="fas fa-home fa-4x icon-orange"></span>
<h3 className="my-3">Choose A Restaurant</h3>
</div>
</div>
<div className="col-md-6 col-lg-4">
<div className="service-box mt-5 mx-auto">
<span className="fas fa-utensils fa-4x icon-orange"></span>
<h3 className="my-3">Choose A Tasty Dish</h3>
</div>
</div>
<div className="col-md-6 col-lg-4">
<div className="service-box mt-5 mx-auto">
<span className="fas fa-shipping-fast fa-4x icon-orange"></span>
<h3 className="my-3">Pick Up Or Delivery</h3>
</div>
</div>
</div>
</div>
</div>
)
}
export default Howitworks;
最佳答案
使用Intersection Observer观察图标的包含 div
何时进入视口(viewport)。 Intersection Observer 是 vanilla JS,不需要任何外部模块或库,并且是为元素在滚动时进入视口(viewport)而构建的。
在这里,我将通过给它一个 id
来使容器 div
易于定位:
<div id="container-intersect" className="container text-center">
...
...
</div>
然后我为 IntersectionObserver
创建一个配置对象:
// threshold controls how much of #container-intersect must
// be in view before firing the callback function. A value
// of 1.0 means that #container-intersect must be entirely
// in view. A value of 0.5 means that #container-intersect
// must be at least 50% in view.
var options = {
root: document.querySelector('body'),
rootMargin: '0',
threshold: 1.0
}
然后我创建了一个新的 observer
,它在 #container-intersect
进入视口(viewport)时触发函数 callback
。
var observer = new IntersectionObserver(callback, options);
var target = document.querySelector('#container-intersect');
observer.observe(target);
回调
在您的元素中触发和淡出。
var callback = function() {
let icons = document.querySelectorAll('.service-box span');
icons.forEach(function(icon, index) {
icons[index].style.opacity = '1';
});
};
您可以将所有这些代码放在组件的 componentDidMount()
生命周期函数中,如下所示:
function Howitworks() {
componentDidMount() {
var options = {
root: document.querySelector('body'),
rootMargin: '0',
threshold: 1.0
}
var observer = new IntersectionObserver(callback, options);
var target = document.querySelector('#container-intersect');
observer.observe(target);
var callback = function() {
let icons = document.querySelectorAll('.service-box span');
icons.forEach(function(icon, index) {
icons[index].style.opacity = '1';
});
};
}
render() {
return (
...
...
);
}
关于javascript - 在 React.js 中滚动显示图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53966517/