我在这个组件中显示一个YouTube视频数组(使用react player),并且在单击自定义play按钮时让它们播放,但是它会播放(并暂停)所有这些视频,而不是当前选定的项。
我正在使用useRef钩子,并且很难找到如何引用选定的视频并只播放该视频(使用键和/或索引):
注意:如果我将useRef钩子和引用从ReactPlayer中删除,则视频根本不播放。
import React, {useState, useRef} from 'react';
import {useStaticQuery, graphql} from 'gatsby';
import ReactPlayer from 'react-player';
import {Button} from '../Buttons/Button';
import './videos.scss';
import '../../Molecules/Cards/cards.scss';
const VideoCards = () => {
const { allVideoCardsJson } = useStaticQuery(
graphql`
query VideoQuery {
allVideoCardsJson {
edges {
node {
title
source
}
}
}
}
`)
let videoRef = useRef();
const [isPlaying, setIsPlaying] = useState(false);
const playVideo = () => {
// this plays/pauses all of the videos
setIsPlaying(!isPlaying);
// this plays the last video in the array
//videoRef.current.getInternalPlayer().playVideo()
}
return (
<div className="card-container__videos">
{allVideoCardsJson.edges.map(({node, index}) => (
<div className="video-card" key={index} isPlaying={isPlaying}>
<ReactPlayer
ref={videoRef}
url={node.source}
width="100%"
pip={true}
controls={true}
playing={isPlaying}
></ReactPlayer>
<Button onClick={playVideo} style={{zIndex:'200'}} label="Play Video"></Button>
</div>
))}
</div>
);
};
export default VideoCards;更新:我能够将eventHandler函数移动到按钮中,并收到相同的结果(播放/暂停所有视频),但我仍然很难找到如何引用键/唯一id并在函数中使用它:
<Button onClick={() => {
if(isPlaying) {
setIsPlaying(false);
} else {
setIsPlaying(true);
}
}} label="Play Video"></Button>发布于 2021-09-15 20:21:09
isPlaying是在映射之外设置的,而不是特定于任何映射索引。
因此,您需要将isPlaying更改为特定于映射的元素。基于allVideoCardsJson创建一个对象,该对象包含每个项的布尔值。然后,将索引或某些标识符作为参数,在playVideo中更新它们。
发布于 2021-09-16 06:17:37
而不是布尔值,而是存储在isPlaying中播放的视频的索引。
将Button onClick更改为:onClicK={() => playVideo(index)}
更改playVideo函数:
const playVideo = i => setIsPlaying(i)
在ReactPlayer中,更改演奏道具:playing={isPlaying === index}
您可能会从包含的div中移除isPlaying道具,不确定这将完成什么工作。
https://stackoverflow.com/questions/69199256
复制相似问题