如何在React+TailwindCSS中仅让react-reveal的Zoom效果在桌面端生效
实现react-reveal Zoom动画仅在桌面端生效
要让react-reveal的Zoom动画只在桌面版本生效、移动端禁用,你可以通过监听窗口尺寸判断设备类型,再结合react-reveal组件的disabled属性实现,具体方案如下:
1. 直接修改现有组件代码
在Pricing组件中添加状态监听窗口尺寸,给Zoom组件加上禁用判断:
import React, { useState, useEffect } from "react"; import { pricing } from "../../database"; import { Fade, Zoom } from "react-reveal"; import { PricingCard } from "../Pricing"; const Pricing = () => { const { email } = pricing; const [isMobile, setIsMobile] = useState(false); useEffect(() => { // 以Tailwind默认的768px为移动端断点,小于该尺寸判定为移动端 const checkMobile = () => { setIsMobile(window.innerWidth < 768); }; // 页面加载时先执行一次检测 checkMobile(); // 监听窗口大小变化,实时更新设备状态 window.addEventListener('resize', checkMobile); // 组件卸载时移除监听,避免内存泄漏 return () => window.removeEventListener('resize', checkMobile); }, []); return ( <div className="flex items-center justify-center mt-40 flex-col dark:text-white"> {/* 移动端禁用Zoom动画 */} <Zoom left cascade disabled={isMobile}> <h1 className="font-bold text-4xl my-3">PRICING</h1> </Zoom> <Zoom disabled={isMobile}> <h2>I will work according to your choice</h2> </Zoom> <div className="flex justify-center gap-10 bg-opacity-50 dark:text-white leading-loose "> <PricingCard /> </div> </div> ); }; export default Pricing;
2. 可选:封装复用性组件
如果多个页面需要类似逻辑,可以封装一个仅在桌面端生效的Zoom组件,避免重复代码:
import React, { useState, useEffect } from 'react'; import { Zoom } from 'react-reveal'; const DesktopZoom = ({ children, ...props }) => { const [isMobile, setIsMobile] = useState(false); useEffect(() => { const checkMobile = () => setIsMobile(window.innerWidth < 768); checkMobile(); window.addEventListener('resize', checkMobile); return () => window.removeEventListener('resize', checkMobile); }, []); return <Zoom disabled={isMobile} {...props}>{children}</Zoom>; }; export default DesktopZoom;
后续在Pricing组件中直接替换原Zoom组件即可:
<DesktopZoom left cascade> <h1 className="font-bold text-4xl my-3">PRICING</h1> </DesktopZoom> <DesktopZoom> <h2>I will work according to your choice</h2> </DesktopZoom>
这样就能确保Zoom动画仅在窗口宽度≥768px的桌面环境触发,移动端自动禁用动画效果。
内容的提问来源于stack exchange,提问作者Sandi-s
相关产品推荐
相关产品推荐

