我正在播放 Youtube 視頻。一旦輸入某些內容,API 服務器將回復一個 URL,該 URL 與 Youtube 的播放器在同一播放器中播放。API 的視頻結束后,如何回傳 YT 視頻?
播放器視頻代碼 (Typescript) 看起來像這樣,它由videoUrlProp處理來自父組件的 URL 回應的狀態提供。
const Player: React.FC<IProps> = ({
onProgress,
videoUrlProp,
}:
IProps) => {
// Don't mind this segment.
const { playerRef, isPlaying } = useStore(
(state) => ({ playerRef: state.playerRef, isPlaying: state.isPlaying }),
shallow
);
// We check if the source is the original. This is used to resize the player.
const isOriginalVideo = videoUrlProp.includes("youtube");
return (
<div className="player">
<ReactPlayer
url={videoUrlProp}
controls={true}
onProgress={onProgress}
width={isOriginalVideo ? "100%" : "70%"}
height={isOriginalVideo ? "100%" : "100%"}
className="react-player"
ref={playerRef}
playing={isPlaying}
/>
</div>
);
};
export default Player;
我正在react-player為播放器使用;這是在父組件中宣告狀態的方式:
const [videoUrl, setVideoUrl] = useState(
"https://www.youtube.com/watch?v=something"
);
歡迎任何幫助。謝謝!
*編輯:我對在 stackoverflow 上提問還是有點陌生??,如果我遺漏了一些資料,或者我是否應該以不同的方式寫下來,請告訴我!泰!:)
uj5u.com熱心網友回復:
狀態沒有“重置”功能。但是很容易模擬它。
如果您設定您的狀態并公開默認/初始值,那么您將擁有以下內容:
const defaultVideoUrl = "https://www.youtube.com/watch?v=something"
然后在你的組件中的某個地方,宣告狀態:
const [videoUrl, setVideoUrl] = useState(defaultVideoUrl);
然后在視頻結束時設定回該默認值,根據檔案,這是使用onEnded道具:
<ReactPlayer
...otherProps
onEnded={() => setVideoUrl(defaultVideoUrl)}
/>
uj5u.com熱心網友回復:
您可以將一個函式 props 傳遞給您的子組件,在視頻結束時呼叫它并使用 useEffect 觸發父組件中的重置。
useEffect(()=> {
if (isVideoFinished) props.reset(true)
}, [isVideoFinished])
并在您的父組件中簡單地做
const reset = (shouldReset) => {
if (shouldReset) {
setVideoUrl('reset to whatever you want')
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389478.html
標籤:javascript 反应 打字稿 反应钩子 反应播放器
