javascript - 带有 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>
</>
你能帮我理解我做错了什么吗?如果您能够为我提供一个工作示例,那将是非常好的和感激的。
解决方案
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)");
推荐阅读
- java - 关于 objectify 的事务入队任务的问题
- google-app-engine - 如何在 Google App Engine 中安装 Errbot
- html - 如何将一个 div 固定到另一个 div 的右侧?
- c# - 无法导出 Excel
- sql - 获取第一列空白postgres
- apache-kafka - 如何在 Kafka 中获取消息而不会丢失?
- python - python,aiohttp,AssertionError:数据参数必须是字节(
) - java - 有没有办法在不使用 Java 密钥库的情况下使用 WebFlux 在 Azure Kubernetes 服务中配置 SSL 证书?
- django - Django:使用 Bootstrap login.html 记录用户时遇到问题
- javascript - 将 CSS 预加载器添加到动态页面加载器