const VideoList = ({ videoList }) => {
let stateArr:any=[]
for(let i=0;i<content.videoListItems.length;i++){
stateArr[i]=true
}
const [iconDisplay, setIconHide] = useState(stateArr);
const stopVideo=(e:any,index:any)=>{
stateArr[index]=true
e.target.parentElement.parentElement.previousSibling.pause();
}
const videoPlay=(e:any,index:any)=>{
stateArr[index]=false
e.target.parentElement.parentElement.previousSibling.play();
}
useEffect(() => {
setIconHide(stateArr);
}, []);
return (
<div>
{videoListItems.map((item: any, index: number) => { //rendering video list
return (
<div key={index}>
<video src={item.video.url} />
<span>
{iconDisplay[index] &&<button onClick={(e:any)=>videoPlay(e,index)}>
<img // rendering play image
src="play.svg"
alt="Play Icon"
/>
</button>}
{!iconDisplay[index] && <button onClick={(e:any)=>stopVideo(e,index)}>
<img
src="pause.svg" //rendering pause image
alt="Pause Icon"
/>
</button>
}
</span>
</div>
)
})
}
</div>
)
}
如何实现此功能。我正在尝试渲染视频列表,并根据事件点击尝试播放和暂停,但不知何故,我无法在第一次点击后渲染暂停图像
通过在array
中管理您的状态,使这一点变得更加复杂。这是可以做到的,但通过设置stateArr[index]=true
来改变状态不是办法。
如果列表中的每个视频都有一个Video
组件,它在内部处理自己的isPlaying
状态,那么您可以让这件事变得更容易。
我使用ref
来访问视频元素,而不是查看DOM父/兄弟关系。
import { useState, useRef } from "react";
type VideoProps = {
src: string; // require an src
} & JSX.IntrinsicElements["video"]; // allow any other props of the HTML <video> element
const Video = (props: VideoProps) => {
const videoRef = useRef<HTMLVideoElement>(null);
const [isPlaying, setIsPlaying] = useState(false);
const togglePlay = () => {
// play or pause the video element
if (isPlaying) {
videoRef.current?.pause();
} else {
videoRef.current?.play();
}
// update the state
setIsPlaying(!isPlaying);
};
return (
<div>
<video
{...props} // pass through all props to the video element
ref={videoRef} // attach the ref
/>
<span>
<button onClick={togglePlay}>
<img
src={isPlaying ? "pause.svg" : "play.svg"}
alt={isPlaying ? "Pause" : "Play"}
/>
</button>
</span>
</div>
);
};
type VideoListProps = {
videoListItems: Array<{
video: {
url: string;
};
}>;
};
const VideoList = ({ videoListItems }: VideoListProps) => {
return (
<div>
{videoListItems.map((item) => (
<Video key={item.video.url} src={item.video.url} />
))}
</div>
);
};