React中鼠标悬停按钮修改state切换ReactPlayer视频URL的实现问题
问题根因
whileHover 是Framer Motion框架专属的交互属性,仅支持在Framer Motion导出的运动组件(如motion.div、motion.button,或经motion()方法包装的自定义组件)上生效,普通自定义<Button/>组件没有集成Framer Motion的事件监听逻辑,直接绑定的whileHover回调不会被触发。
可行解决方案
方案1:按钮外层包裹Motion容器(已验证可生效)
你提到的外层包裹motion.wrapper本质是用Framer Motion的通用运动容器承载普通Button,将悬停回调绑定在运动容器上即可触发执行,完整示例代码如下:
import { motion } from "framer-motion" import ReactPlayer from "react-player" import { useState } from "react" import Button from "你的Button组件路径" const VideoBackgroundComponent = () => { const [videoUrl, setVideoUrl] = useState("videos/planet.mp4") return ( <div> <div> {/* 外层包裹motion.div作为运动容器 */} <motion.div whileHover={() => setVideoUrl("videos/Transition.mp4")} // 按需补充鼠标离开切回原视频的逻辑 onMouseLeave={() => setVideoUrl("videos/planet.mp4")} > <Button>testbutton</Button> </motion.div> </div> <motion.div className="react-player.full"> <ReactPlayer url={videoUrl} width="120%" height="120%" playing={true} loop={true} align="center" /> </motion.div> </div> ) } export default VideoBackgroundComponent
同时修正原代码的两个小问题:
class属性在React中要写为classNameplaying、loop需要传入布尔值而非字符串,避免组件属性识别异常
方案2:直接包装自定义Button为Motion组件
如果不想额外增加DOM层级,可以用motion()方法直接包装你的自定义Button,包装后的组件原生支持所有Framer Motion交互属性:
// 包装自定义Button const MotionButton = motion(Button) // 组件内直接使用 <MotionButton whileHover={() => setVideoUrl("videos/Transition.mp4")} onMouseLeave={() => setVideoUrl("videos/planet.mp4")} > testbutton </MotionButton>
内容的提问来源于stack exchange,提问作者thebig Dev
相关产品推荐
相关产品推荐

