[英]How to set refs in React useRef
I'm trying to play a gsap animation on component did mount in a Gatsby site but my refs aren't being applied.我正在尝试在 Gatsby 站点中安装的组件上播放 gsap 动画,但我的引用没有被应用。
const PricingList = ({ classes }) => {
let pricingCard = useRef([]);
useEffect(() => {
console.log('start Animation', pricingCard.current);
TweenMax.staggerFrom(pricingCard.current, 0.4, { opacity: 0, y: 100 }, 0.5);
}, []);
return (
<StaticQuery
query={graphql`
{
Prices: contentfulConfig {
pricing {
priceBand {
title
price
}
priceBand2 {
price
title
}
priceBand3 {
price
title
}
}
}
}
`}
render={(data) => (
<Fragment>
<div className={classes.Container}>
<PricingItem
ref={(el) => {
pricingCard.current[0] = el;
}}
/>
<PricingItem
ref={(el) => {
pricingCard.current[1] = el;
}}
/>
<PricingItem
ref={(el) => {
pricingCard.current[2] = el;
}}
/>
</div>
</Fragment>
)}
/>
);
};
I have tried -我试过了 -
pricingCard.current.push(el);
without any luck, I just get an empty array in console.运气不好,我只是在控制台中得到一个空数组。
I have also tried -我也试过——
useEffect(() => {
console.log('start Animation', pricingCard.current);
TweenMax.staggerFrom(pricingCard.current, 0.4, { opacity: 0, y: 100 }, 0.5);
}, [pricingCard]);
Thinking it might need to wait to be updated after the component mounted, but no luck.认为它可能需要在组件安装后等待更新,但没有运气。
Any help would be appreciated.任何帮助,将不胜感激。
Thanks in advance.提前致谢。
For animation you might want to use useLayoutEffect
instead of useEffect
.对于动画,您可能希望使用
useLayoutEffect
而不是useEffect
。
Is it going to be always 3 PricingItem
s?它会一直是 3
PricingItem
吗? In this case you can create 3 separate refs for each ( const pricingItem1 = useRef(null)
) and in render <PricingItem ref={pricingItem1} />
.在这种情况下,您可以为每个 (
const pricingItem1 = useRef(null)
) 创建 3 个单独的 refs,并在 render <PricingItem ref={pricingItem1} />
。
Also can you confirm that the function from the render prop has been called?您还可以确认渲染道具中的函数已被调用吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.