我在這個組件中顯示了一個YouTube視頻陣列(使用react-player),并在點擊自定義播放按鈕時播放了這些視頻,但它播放(和暫停)了所有的視頻,而不是當前選定的專案。
我正在使用 useRef 鉤子,但我不知道如何參考一個選定的視頻并只播放該視頻(使用鍵和/或索引):
注意:如果我從ReactPlayer中移除useRef鉤子和ref,視頻根本無法播放
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/Card/cards.scss';
const VideoCards = (/span>) => {
const { allVideoCardsJson } = useStaticQuery(
graphql`.
query VideoQuery {
allVideoCardsJson {
邊緣 {
節點 {
標題
來源
}
}
}
}
`)
let videoRef = useRef();
const [isPlaying, setIsPlaying] = useState(false)。
const playVideo = (/span>) => {
//這個播放/暫停所有的視頻。
setIsPlaying(!isPlaying);
//this plays the last video in the array.
//videoRef.current.getInternalPlayer().playVideo()。
}
return (
<div className="card-container__videos">/span>
{allVideoCardsJson.edges.map(({node, index}) => (
< div className="video-card" key={index} isPlaying={isPlaying}>
<ReactPlayer。
ref={videoRef}
url={節點.原始碼}
width="100%"
pip={true}
controls={true}{/span>
playing={isPlaying}。
</ReactPlayer>>
<Button onClick={playVideo} style={zIndex: '200'}}。label="Play Video"></Button>
</div>
))}
</div>>
);
};
export default VideoCards;
更新:我能夠將eventHandler函式移到Button中,并收到相同的結果(播放/暫停所有視頻),但我仍然難以弄清楚如何參考一個關鍵/唯一的id并在函式中使用它:
<Button onClick={( ) => {
if(isPlaying) {
setIsPlaying(false) 。
} else {
setIsPlaying(true)。
}
}} label="Play Video"> </Button>
uj5u.com熱心網友回復:
isPlaying是在地圖之外設定的,并不特定于任何映射的索引。
所以你需要改變isPlaying,使其特定于映射的元素。創建一個基于allVideoCardsJson的物件,其中包含每個專案的布林值。然后,在playVideo中更新它們,讓它接受索引或一些識別符號作為引數。
uj5u.com熱心網友回復:
代替一個布林值,在isPlaying中存盤正在播放的視頻的索引
將Button onClick改成。onClicK={() => playVideo(index)}
const playVideo = i => setIsPlaying(i)
在ReactPlayer中改變播放道具。playing={isPlaying === index}
在ReactPlayer中改變播放道具:playing={isPlaying === index}
你也許可以從包含的DIV中洗掉isPlaying道具,不知道這樣做有什么用
。轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/306903.html
標籤:
上一篇:如何動態地創建一個陣列的陣列?
