在 React 应用中嵌入 Youtube 视频的最简单方法
概述
- 快速、简单
- 不
npm i
- 充分响应
- 随意复制和粘贴
1.为iframe制作一个组件:
YoutubeEmbed.js
import React from "react";
import PropTypes from "prop-types";
const YoutubeEmbed = ({ embedId }) => (
<div className="video-responsive">
<iframe
width="853"
height="480"
src={`https://www.youtube.com/embed/${embedId}`}
frameBorder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
title="Embedded youtube"
/>
</div>
);
YoutubeEmbed.propTypes = {
embedId: PropTypes.string.isRequired
};
export default YoutubeEmbed;
2. 添加一些 CSS 以实现响应能力:
样式.css
.video-responsive {
overflow: hidden;
padding-bottom: 56.25%;
position: relative;
height: 0;
}
.video-responsive iframe {
left: 0;
top: 0;
height: 100%;
width: 100%;
position: absolute;
}
3. 使用它
再简单不过了。轻松便捷:
import React from "react";
import "./styles.css";
import YoutubeEmbed from "./YoutubeEmbed";
export default function App() {
return (
<div className="App">
<h1>Youtube Embed</h1>
<YoutubeEmbed embedId="rokGy0huYEA" />
</div>
);
}