键盘左右箭头按钮控制视频切换

This commit is contained in:
北枳 2025-07-07 12:59:35 +08:00
parent 27f18ee5ac
commit a6b1be4e63

View File

@ -1,6 +1,6 @@
'use client'; // Add this to ensure it's a client component 'use client'; // Add this to ensure it's a client component
import React, { useState, useRef, useEffect } from 'react'; import React, { useState, useRef, useEffect, useCallback } from 'react';
import { ChevronLeft, ChevronRight, Volume2, VolumeX, Play, Pause } from 'lucide-react'; import { ChevronLeft, ChevronRight, Volume2, VolumeX, Play, Pause } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import dynamic from 'next/dynamic'; import dynamic from 'next/dynamic';
@ -76,15 +76,15 @@ function VideoScreenLayoutComponent({ videos }: VideoScreenLayoutProps) {
}; };
// 应用音量设置到视频元素 // 应用音量设置到视频元素
const applyVolumeSettings = (videoElement: HTMLVideoElement) => { const applyVolumeSettings = useCallback((videoElement: HTMLVideoElement) => {
if (videoElement) { if (videoElement) {
videoElement.volume = volume; videoElement.volume = volume;
videoElement.muted = isMuted; videoElement.muted = isMuted;
} }
}; }, [volume, isMuted]);
// 处理切换 // 处理切换
const handleSlide = (direction: 'prev' | 'next') => { const handleSlide = useCallback((direction: 'prev' | 'next') => {
if (isAnimating) return; if (isAnimating) return;
setIsAnimating(true); setIsAnimating(true);
@ -112,7 +112,7 @@ function VideoScreenLayoutComponent({ videos }: VideoScreenLayoutProps) {
} }
} }
}, 500); }, 500);
}; }, [isAnimating, currentIndex, videos.length, isPlaying, applyVolumeSettings]);
// 音量设置变化时应用到当前视频 // 音量设置变化时应用到当前视频
useEffect(() => { useEffect(() => {
@ -120,7 +120,7 @@ function VideoScreenLayoutComponent({ videos }: VideoScreenLayoutProps) {
if (currentVideo) { if (currentVideo) {
applyVolumeSettings(currentVideo); applyVolumeSettings(currentVideo);
} }
}, [volume, isMuted, currentIndex]); }, [volume, isMuted, currentIndex, applyVolumeSettings]);
// 播放状态变化时应用到当前视频 // 播放状态变化时应用到当前视频
useEffect(() => { useEffect(() => {
@ -142,6 +142,33 @@ function VideoScreenLayoutComponent({ videos }: VideoScreenLayoutProps) {
setIsPlaying(!isPlaying); setIsPlaying(!isPlaying);
}; };
// 键盘事件监听器 - 添加左右箭头键控制
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
// 检查是否正在动画中,如果是则不处理
if (isAnimating) return;
switch (event.key) {
case 'ArrowLeft':
event.preventDefault(); // 阻止默认行为
handleSlide('prev');
break;
case 'ArrowRight':
event.preventDefault(); // 阻止默认行为
handleSlide('next');
break;
}
};
// 添加键盘事件监听器
window.addEventListener('keydown', handleKeyDown);
// 清理函数 - 组件卸载时移除监听器
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
}, [isAnimating, handleSlide]); // 添加handleSlide到依赖项
return ( return (
<div className="relative w-full h-[360px] overflow-hidden bg-[var(--background)]"> <div className="relative w-full h-[360px] overflow-hidden bg-[var(--background)]">
{/* 视频面板容器 */} {/* 视频面板容器 */}