gpt4 book ai didi

javascript - 在 YouTube iframe 的 'removeChild ' 上 react 'Node'

转载 作者:行者123 更新时间:2023-12-03 08:43:11 34 4
gpt4 key购买 nike

Codesandbox here

我有一个渲染 div 的组件,并在安装时将 youtube iframe 插入到该 div 中。我希望能够切换此组件以显示和隐藏它。但是,每当我“隐藏”组件(卸载它)时,我都会收到以下错误消息:

Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

如何卸载该组件?谢谢。

index.tsx:

import * as React from "react";
import ReactDOM from "react-dom";

declare global {
interface Window {
YT: any;
onYouTubeIframeAPIReady: Function;
}
}

const YoutubePlayer: React.FC = () => {
const videoFrameId = "youtube-player-1";
const onPlayerReady = (event: { [key: string]: any }): void => {
event.target.playVideo();
};

React.useEffect(() => {
const loadVideo = (): void => {
new window.YT.Player(videoFrameId, {
videoId: "5qap5aO4i9A",
events: {
onReady: onPlayerReady
}
});
};

// If not, load the script asynchronously
if (!window.YT) {
const tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";

// onYouTubeIframeAPIReady will load the video after the script is loaded
window.onYouTubeIframeAPIReady = loadVideo;

const firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
} else {
// If script is already there, load the video directly
loadVideo();
}
}, []);

return <div id={videoFrameId} />;
};

export default YoutubePlayer;

const App: React.FC = () => {
const [show, setShow] = React.useState<boolean>(false);
return (
<>
<button type="button" onClick={() => setShow(prevState => !prevState)}>
{show ? "Hide Player" : "Show Player"}
</button>
{show && <YoutubePlayer />}
</>
);
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

最佳答案

应该是一个非常简单的修复。为玩家提供一个定义的父元素。

{show && <div><YoutubePlayer /></div>}

而不是

{show && <YoutubePlayer />}

removeChild 调用不应失败。


编辑:或者更好的是,在内部进行,这样调用者就不需要进行包装。

return <div><div id={videoFrameId} /></div>;

代替

return <div id={videoFrameId} />;

关于javascript - 在 YouTube iframe 的 'removeChild ' 上 react 'Node',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62237684/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com