如何在 React 頁面嵌入 youtube 影片
· 2 分鐘閱讀
使用 iframe 是最直接的方法,在 youtube 影片點選右鍵,選「複製嵌入程式碼」,可以得到像下面的這段程式碼
<iframe width="640" height="360" src="https://www.youtube.com/embed/daVASrwlU9c" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
把這段程式碼貼進 React 可以運作,但是沒有 RWD 的效果,google 了一下找 到解法,不多廢話,直接附程式碼
CSS
RwdYoutube.module.css
.videobox {
position: relative;
width: 100%;
height: 0;
padding-bottom: 56.25%;
}
.videobox iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}