Reactjs 从其他组件访问react组件中的videojs播放器
我使用videojs文档中的指南创建了一个正常工作的组件(见下文)。加载后,我还可以使用API函数(如Reactjs 从其他组件访问react组件中的videojs播放器,reactjs,video.js,Reactjs,Video.js,我使用videojs文档中的指南创建了一个正常工作的组件(见下文)。加载后,我还可以使用API函数(如window.player.play())从控制台控制播放器 我现在想创建一个播放/暂停按钮组件。如果我只使用onClick={window.player.play},则当页面加载时,播放器不存在,并导致错误 我希望播放/暂停组件是VideoPlayer的兄弟: <div> <VideoPlayer props /> <PlayButton />
window.player.play()
)从控制台控制播放器
我现在想创建一个播放/暂停按钮组件。如果我只使用onClick={window.player.play}
,则当页面加载时,播放器不存在,并导致错误
我希望播放/暂停组件是VideoPlayer的兄弟:
<div>
<VideoPlayer props />
<PlayButton />
<PauseButton />
</div>
从其他组件访问我的播放器的最佳方式是什么
import React from 'react';
export default class VideoPlayer extends React.Component {
componentDidMount() {
// instantiate video.js
this.player = window.videojs(this.videoNode, this.props, function onPlayerReady() {
console.log('onPlayerReady', this)
});
window.player = this.player;
}
// destroy player on unmount
componentWillUnmount() {
if (this.player) {
this.player.dispose()
}
}
// wrap the player in a div with a `data-vjs-player` attribute
// so videojs won't create additional wrapper in the DOM
// see https://github.com/videojs/video.js/pull/3856
render() {
return (
<div data-vjs-player>
<video ref={ node => this.videoNode = node } className="video-js"></video>
</div>
)
}
}
从“React”导入React;
导出默认类VideoPlayer扩展React.Component{
componentDidMount(){
//实例化video.js
this.player=window.videojs(this.videoNode,this.props,函数onPlayerReady()){
console.log('onPlayerReady',this)
});
window.player=this.player;
}
//卸载时摧毁玩家
组件将卸载(){
if(this.player){
this.player.dispose()
}
}
//使用'datavjsplayer'属性将播放器包装在div中
//所以videojs不会在DOM中创建额外的包装器
//看https://github.com/videojs/video.js/pull/3856
render(){
返回(
this.videoNode=node}className=“video js”>
)
}
}
您不应该在onClick
事件上直接调用window.player
,因为每次组件渲染时都会调用它onClick
需要一个函数
,因此您可以像这样调用它
onClick = {() => {if(window.player) {window.player.play()}}}
我假设您的播放和暂停按钮将是VideoPlayer组件的子组件。这是正确的吗?啊,不-他们将成为顶级组件检查这个答案,即使组件是顶级组件,它也应该工作!是的但是需要调用play(),所以-onClick={()=>{if(window.player){window.player.play()}}正在工作