简体   繁体   中英

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.

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 .

Is it going to be always 3 PricingItem s? In this case you can create 3 separate refs for each ( const pricingItem1 = useRef(null) ) and in render <PricingItem ref={pricingItem1} /> .

Also can you confirm that the function from the render prop has been called?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM