如何在没有外部库的情况下在 React 中播放 <video></video>?
How to play <video></video> in React without external library?
我的网页中有一个视频标签和一个 "play/pause" 按钮,当用户点击它时,视频应该 start/stop 播放。不幸的是,此解决方案不起作用 (). Is there any chance that there is a conflict with the react-slick carousel(https://react-slick.neostack.com/)?
这是我的代码:
import React from "react";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
class VideoCarousel extends Component {
playVideo() {
this.refs.vidRef.play();
}
componentRender(data) {
const settings = {
dots: true,
...
};
return (
<div id="video-carousel">
<div>
<Slider {...settings}>
{data.map((item, index) => (
<div key={index}>
<div className="video">
<div className="w-100 h-100">
<video className="video-carousel-card-video" ref="vidRef">
<source src={item.video_file} type="video/mp4" />
</video>
<button className="card-video-button" onClick={this.playVideo.bind(this)}>
</button>
</div>
</div>
</div>
))}
</Slider>
</div>
</div >
)
}
}
export default VideoCarousel;
我注意到几件事:
您应该为 class 定义引用,例如 this example from the docs,因为不推荐使用 this.refs
:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
然后您可以像这样定义播放函数:
playVideo() {
this.myRef.current.play();
}
其次,您缺少 render
函数,所有 class 组件都需要它。
最后,data
来自哪里?我没有看到它在任何地方定义,你也没有通过 state 或 props 访问它。
问题出在 ref="vidRef" 上。由于它嵌套到 forEach() 函数,它创建了多个对不同元素的引用,因此 play() 函数没有特定的引用。
我的网页中有一个视频标签和一个 "play/pause" 按钮,当用户点击它时,视频应该 start/stop 播放。不幸的是,此解决方案不起作用 (
这是我的代码:
import React from "react";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
class VideoCarousel extends Component {
playVideo() {
this.refs.vidRef.play();
}
componentRender(data) {
const settings = {
dots: true,
...
};
return (
<div id="video-carousel">
<div>
<Slider {...settings}>
{data.map((item, index) => (
<div key={index}>
<div className="video">
<div className="w-100 h-100">
<video className="video-carousel-card-video" ref="vidRef">
<source src={item.video_file} type="video/mp4" />
</video>
<button className="card-video-button" onClick={this.playVideo.bind(this)}>
</button>
</div>
</div>
</div>
))}
</Slider>
</div>
</div >
)
}
}
export default VideoCarousel;
我注意到几件事:
您应该为 class 定义引用,例如 this example from the docs,因为不推荐使用 this.refs
:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
然后您可以像这样定义播放函数:
playVideo() {
this.myRef.current.play();
}
其次,您缺少 render
函数,所有 class 组件都需要它。
最后,data
来自哪里?我没有看到它在任何地方定义,你也没有通过 state 或 props 访问它。
问题出在 ref="vidRef" 上。由于它嵌套到 forEach() 函数,它创建了多个对不同元素的引用,因此 play() 函数没有特定的引用。