[英]intersectionobserver inside useEffect only fires once
I am attempting to make style class on and off when it is observed, but it works only once.我试图在观察时打开和关闭 class 样式,但它只工作一次。 i guess it may be solved with obs.unobserve or obs.disconnect, but i failed to write a code in right way.
我想它可以用 obs.unobserve 或 obs.disconnect 解决,但我没有以正确的方式编写代码。 Here is the code.
这是代码。 (simplified)
(简化)
useEffect(() => {
const obs = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
$('.class-a').addClass('white');
}
else {
$('.class-a').addClass('black');
}
})
}, { threshold: [0.5] });
obs.observe(document.querySelector('.sub'));
}, [])
You are only querying a single selector.您只查询一个选择器。 If you want to query more than one, you would have to use
document.querySelectorAll()
.如果要查询多个,则必须使用
document.querySelectorAll()
。
Edit try this (querying them on their own won't work, have to actually loop through them as well):编辑试试这个(自己查询它们是行不通的,实际上也必须遍历它们):
const list = document.querySelectorAll('.sub');
list.forEach((el) => {
obs.observe(el);
})
Referring to these mdn docs参考这些 mdn 文档
Working non-react test: https://codepen.io/shikkaba/pen/eYMVXXX工作非反应测试: https://codepen.io/shikkaba/pen/eYMVXXX
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.