0

我尝试将 react-intersection-observer 和 framer 运动结合使用,以便在组件处于视图中时使用 useInView 挂钩启动动画。虽然它从大约 1100px 开始工作,但它不适用于移动视图。这是我下面的代码

import Image from "next/image";
import { useRouter } from "next/router";
import { motion, useAnimation } from "framer-motion";

import profile from "../images/profile.jpg";
import { useInView } from "react-intersection-observer";
import { useEffect } from "react";
const HeroSection = () => {
    const router = useRouter();
    const { ref, inView } = useInView({
        threshold: 0.2,
    });
    const animation = useAnimation();

    const heroAnimation = {
        hide: {
            x: -1000,
            opacity: 0,
        },
        show: {
            x: 0,
            opacity: [0.1, 1],
            transition: { delay: 0.3, duration: 0.75, type: "spring", bounce: 0.2 },
        },
    };

    useEffect(() => {
        if (!inView) {
            animation.start("hide");
        }
        if (inView) {
            animation.start("show");
        }
    }, [inView, animation]);

    console.log(inView);

    return (
        <motion.div
            animate={animation}
            variants={heroAnimation}
            ref={ref}
            className='space-y-10 px-4 flex flex-col md:grid md:grid-cols-2 md:py-12 bg-white pb-[50px]'>
            <div className='flex flex-col justify-center items-center space-y-10'>
                <h1 className='text-5xl mt-[50px] md:mt-0'>Welcome!</h1>
                <p className='text-center max-w-[400px] lg:max-w-[650px]'> website intro
                </p>
                <button
                    onClick={() => router.push("/about")}
                    className='bg-gray-200 shadow-md text-gray-700 font-bold p-3 lg:p-4 rounded-lg active:bg-gray-300 active:shadow-lg hover:scale-105 transition duration-200 ease-in-out'>
                    READ MORE..
                </button>
            </div>

            <div className='rounded-lg relative m-auto h-[350px] w-[280px] md:h-[400px] md:w-[320px] lg:h-[500px] lg:w-[400px]'>
                <Image
                    className='rounded-lg'
                    objectFit='contain'
                    layout='fill'
                    src={profile}
                    alt='profile'
                />
            </div>
        </motion.div>
    );
};

export default HeroSection;
4

1 回答 1

0

有类似的问题。原来它正在工作,最初的 x 值太大了。这应该可以正常工作。

const heroAnimation = {
        hide: {
            x: -50,
            opacity: 0,
        },
        show: {
            x: 0,
            opacity: [0.1, 1],
            transition: { delay: 0.3, duration: 0.75, type: "spring", bounce: 0.2 },
        },
    };

于 2021-12-03T10:42:02.963 回答