javascript - 触发 useState
问题描述
我有一个组件并使用不同的道具有条件地渲染它。
{activeNavItem === 'Concept Art' ? (
<Gallary
images={conceptArtImages}
sectionRef={sectionRef}
/>
) : (
<Gallary
images={mattePaintingImages}
sectionRef={sectionRef}
/>
)}
这个组件有useState(false)
和useEffect
钩子。useEffect
确定屏幕位置何时到达 dom 元素并触发useState
到true
: elementPosition < screenPosition
。然后我state
在 dom 元素上的触发器类:state ? 'animationClass' : ''
。
const Gallary = ({ images, sectionRef }) => {
const [isViewed, setIsViewed] = useState(false);
useEffect(() => {
const section = sectionRef.current;
const onScroll = () => {
const screenPosition = window.innerHeight / 2;
const sectionPosition = section.getBoundingClientRect().top;
console.log(screenPosition);
if (sectionPosition < screenPosition) setIsViewed(true);
};
onScroll();
window.addEventListener('scroll', onScroll);
return () => {
window.removeEventListener('scroll', onScroll);
};
}, [sectionRef]);
return (
<ul className="section-gallary__list">
{images.map((art, index) => (
<li
key={index}
className={`section-gallary__item ${isViewed ? 'animation--view' : ''}`}>
<img className="section-gallary__img" src={art} alt="concept art" />
</li>
))}
</ul>
);
};
问题:它适用于我的第一次渲染。但是当我用不同的道具切换组件时,我state
最初是true
并且我没有动画。
我注意到,如果我有两个组件(ComponentA, ComponentB
)而不是一个(ComponentA
),它可以正常工作。
解决方案
isViewed
当您的组件不在视图中时,请尝试设置为 false,如下所示:
if (sectionPosition < screenPosition && !isViewed){
setIsViewed(true);
}
else{
if(isViewed)
setIsViewed(false);
}
你可以这样做:
if (sectionPosition < screenPosition && !isViewed){
setIsViewed(state=>!state);
}
else{
if(isViewed)
setIsViewed(state=>!state);
}
加上不需要多次渲染同一个组件,你可以只更改道具:
<Gallary
images={activeNavItem === 'ConceptArt'?conceptArtImages:mattePaintingImages}
sectionRef={sectionRef}
/>
推荐阅读
- firebase - Firebase / Google Cloud Function cron 函数返回 INVALID_ARGUMENT
- java - 在“Last Exec”下,使用 JVM 的字符串重复数据删除设置,为什么这么多被列为“重复数据删除”,而很少有人被描述为“新”
- wordpress - 如何修复“WordPress 无法写入某些文件”错误,管理员无法更改网站
- android - Kotlin - 缩放画布性能问题
- r - 循环遍历数据框时如何引用同一行中的元素?
- c# - 在启动时访问 dbcontext
- android - Android WebView和html透明背景
- sql - 哪种商店类型按销售金额和销售数量销售的产品最多
- python - 从numpy中的图像中提取缩略图
- sap-cloud-sdk - 构建失败,例如应用程序 cloud-s4-sdk-book(集成测试)