首页 > 解决方案 > 带有 Framer Motion 的 Next.js 中的“window.innerWidth < 768”

问题描述

我想控制动画(Framer Motion)何时可以使用 运行window.innerWidth,但在 Next.js 中我收到以下错误消息:

ReferenceError: window is not defined

这是我的名为 ValuesSection.jsx 的组件的简化版本:

import React, { useEffect } from "react";
import { useInView } from "react-intersection-observer";
import { motion, useAnimation } from "framer-motion";

export default function ValuesSection() {
  const controls = useAnimation();
  const [ref, inView] = useInView();
  const MobileView = {};
  const isMobile = window.innerWidth < 768;
  if (!isMobile) {
    MobileView = {
      visible: { y: 0, scale: 1 },
      hidden: { y: 250, scale: 0 },
    };
  }

  useEffect(() => {
    if (inView) {
      controls.start("visible");
    }
  }, [controls, inView]);

  return (
<>
 <motion.div
  key={value.name}
  ref={ref}
  animate={controls}
  initial="hidden"
  variants={MobileView}
 >Some content</motion.div>
</>

你能帮我理解我做错了什么吗?如果您能够为我提供一个工作示例,那将是非常好的和感激的。

标签: javascriptreactjsnext.jsframer-motion

解决方案


materiial ui在 next.js 项目中使用屏幕大小的最佳方法是,当屏幕宽度大于或小于定义的值时,您可以使用代表真或假的 Hook ,在我看来它比定义的值更好,window因为它有很多选项你可以在这里使用的是你应该一步一步做的事情

如果您还没有安装材料 ui,请先安装

// with npm
npm install @material-ui/core

// with yarn
yarn add @material-ui/core

然后在您的组件中导入并定义它

import { useMediaQuery } from "@material-ui/core";


export default function ValuesSection() {

const IsTabletOrPhone = useMediaQuery("(max-width:1024px)");

现在如果你的屏幕尺寸比1024px它返回的大false,否则它会返回,true
所以你可以使用它

  if (!IsTabletOrPhone) {
    MobileView = {
      visible: { y: 0, scale: 1 },
      hidden: { y: 250, scale: 0 },
    };
  }

更新:

也许是因为我给它分配了一个大写字母,您可以尝试将名称更改为isTabletOrPhone 小写,如果这不起作用尝试将其更改let

let isTabletOrPhone = useMediaQuery("(max-width:1024px)");

推荐阅读