Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs Ref返回null,但它不是’;t(空)?_Reactjs - Fatal编程技术网

Reactjs Ref返回null,但它不是’;t(空)?

Reactjs Ref返回null,但它不是’;t(空)?,reactjs,Reactjs,我想做一个视频播放器。 视频加载得很好,当我按play时,它就会被播放,以此类推。 当我想显示它的持续时间时,会出现问题。 我试图通过ref访问它。它得到视频,但ref返回空值?我是控制台日志记录,其中包括持续时间。 以下是一幅图像: 添加:我在componentDidMount()中调用ref,只是想看看它是否被“捕获”。 代码如下: import React from 'react'; import ReactDOM from 'react-dom'; class Show extend

我想做一个视频播放器。 视频加载得很好,当我按play时,它就会被播放,以此类推。 当我想显示它的持续时间时,会出现问题。 我试图通过ref访问它。它得到视频,但ref返回空值?我是控制台日志记录,其中包括持续时间。 以下是一幅图像:

添加:我在
componentDidMount()
中调用ref,只是想看看它是否被“捕获”。 代码如下:

import React from 'react';
import ReactDOM from 'react-dom';

class Show extends React.Component {

    constructor(props) {

        super(props);
        this.state = {
            video: "",
            switch: false,
            remaining: null,
        };
        this.playPause = this.playPause.bind(this);
        this.videoRef = React.createRef();
        this.trackTime = this.trackTime.bind(this);
        this.volume = this.volume.bind(this);
        this.fullScreen = this.fullScreen.bind(this);

    }

    fullScreen(){

        let elem = this.videoRef.current;
        if (elem.requestFullscreen){
            elem.requestFullscreen();
          } 
          else if (elem.mozRequestFullScreen){ /* Firefox */
            elem.mozRequestFullScreen();
          } 
          else if (elem.webkitRequestFullscreen){ /* Chrome, Safari & Opera */
            elem.webkitRequestFullscreen();
          } 
          else if (elem.msRequestFullscreen){ /* IE/Edge */
            elem.msRequestFullscreen();
          }

    }

    volume(e){
        this.videoRef.current.volume = e.target.value/100;
    }

    trackTime(e){
        this.setState({
            remaining: e.target.duration - e.target.currentTime,
        });
    }

    playPause(){

        this.setState({
            switch: !this.state.switch
        });

        if(this.videoRef.current.paused){
            this.videoRef.current.play();
        }
        else{
            this.videoRef.current.pause();
        }

    }

    componentDidMount(){

        let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");

        let urlId = window.location.href;
        let getaVideoIdId = urlId.lastIndexOf("/");
        let videoId = urlId.substring(getaVideoIdId+1, urlId.length);

        $.ajax({
            url: '/showAjax',
            type: 'POST',
            data: {_token: token , message: "bravo", videoId: videoId},
            dataType: 'JSON',
            success: (response) => { 
                console.log("success");
                //console.log(response);
                this.setState({
                    video: response.video,
                }); 

            },
            error: (response) => {
                console.log("error");
                console.log(response);
            }
        }); 
        console.log(this.videoRef);
        //this.videoRef.current.play();
    }

    render(){
        //console.log(this.state);

        let PlayPause = this.state.switch ? "fa fa-pause-circle" : "fa fa-play-circle";

        let minutes = Math.floor(this.state.remaining/60);
        minutes = (""+minutes).length===1 ? "0"+minutes : minutes;//Checks if mins are one digit by turning it into string that now beasues length, if length is 1(single digit), if it is, then adds zero in front of it.
        let seconds = Math.floor(this.state.remaining%60);
        seconds = (""+seconds).length===1 ? "0"+seconds : seconds;//Same as mins, but for seconds.
        let remainingTime = minutes+" : "+seconds;

        let videoUrl = this.state.video && this.state.video.name ? "/storage/"+this.state.video.user.name+"'s Videos/"+this.state.video.name : null;

        let video = videoUrl ? <div  className={"videoWrapper"}><video ref={this.videoRef} preload="auto" onTimeUpdate={this.trackTime}>
            <source src={videoUrl} type="video/mp4"/>
            <source src={videoUrl} type="video/ogg"/>
            Your browser does not support the video tag.
            </video>
            <div id="controls">

                <button className="btnV" onClick={this.playPause}><i className={PlayPause}></i></button>
                <div className="time">{remainingTime}</div>
                <input type="range" className="custom-range" id="customRange" name="points1" onChange={this.volume}/>
                <div className="time" onClick={this.fullScreen}><i className="fa fa-expand"></i></div>

            </div>
        </div> : "";

        return (
            <div className="container">
                {video}
            </div>
        );

    }

}

if(document.getElementById('show')){

    ReactDOM.render(<Show/>, document.getElementById('show'));

}
从“React”导入React;
从“react dom”导入react dom;
类Show扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
视频:“,
开关:错误,
剩余:空,
};
this.playPause=this.playPause.bind(this);
this.videoRef=React.createRef();
this.trackTime=this.trackTime.bind(this);
this.volume=this.volume.bind(this);
this.fullScreen=this.fullScreen.bind(this);
}
全屏(){
设elem=this.videoRef.current;
if(元素请求全屏){
元素请求全屏();
} 
else if(elem.mozRequestFullScreen){/*Firefox*/
elem.mozRequestFullScreen();
} 
else if(elem.webkitRequestFullscreen){/*Chrome、Safari和Opera*/
elem.webkitRequestFullscreen();
} 
else if(elem.msRequestFullscreen){/*IE/Edge*/
elem.msRequestFullscreen();
}
}
卷(e){
this.videoRef.current.volume=e.target.value/100;
}
轨道时间(e){
这是我的国家({
剩余:e.target.duration-e.target.currentTime,
});
}
播放暂停(){
这是我的国家({
开关:!this.state.switch
});
如果(此.videoRef.current.paused){
这个.videoRef.current.play();
}
否则{
这个.videoRef.current.pause();
}
}
componentDidMount(){
让token=document.querySelector(“meta[name='csrf-token']”)。getAttribute(“content”);
让urlId=window.location.href;
让getavideoid=urlId.lastIndexOf(“/”);
让videoId=urlId.substring(getavideoid+1,urlId.length);
$.ajax({
url:“/showAjax”,
键入:“POST”,
数据:{令牌:令牌,消息:“好极了”,videoId:videoId},
数据类型:“JSON”,
成功:(响应)=>{
控制台日志(“成功”);
//控制台日志(响应);
这是我的国家({
视频:response.video,
}); 
},
错误:(响应)=>{
控制台日志(“错误”);
控制台日志(响应);
}
}); 
console.log(this.videoRef);
//这个.videoRef.current.play();
}
render(){
//console.log(this.state);
让播放暂停=this.state.switch?“fa-fa暂停圈”:“fa-fa播放圈”;
让分钟数=数学楼层(本状态剩余/60);
分钟=(“”+分钟)。长度===1?“0”+分钟:分钟;//通过将分钟转换为现在显示长度的字符串来检查分钟是否为一位数字,如果长度为1(单个数字),如果是,则在其前面加零。
让秒数=数学地板(此状态剩余%60);
秒=(“”+秒)。长度===1?“0”+秒:秒;//与分钟相同,但为秒。
让剩余时间=分钟+“:”+秒;
让videoUrl=this.state.video&&this.state.video.name?/storage/“+this.state.video.user.name+“'s Videos/”+this.state.video.name:null;
让视频=视频URL?
您的浏览器不支持视频标记。
{剩余时间}
: "";
返回(
{视频}
);
}
}
if(document.getElementById('show')){
ReactDOM.render(,document.getElementById('show'));
}
Edit1:当我刷新页面时,自动播放也不总是起作用。。。并显示“Uncaught(in promise)DOMException”。

componentDidMount()
在安装组件后立即调用

在调用
componentDidMount()
之前,将调用
render()
,以初始化DOM

但是,在
render()
中,您确实喜欢以下内容:

let videoUrl = this.state.video
   && this.state.video.name ? "/storage/"+this.state.video.user.name+"'s Videos/"+this.state.video.name : null;

let video = videoUrl ? <div  className={"videoWrapper"}><video ref={this.videoRef} preload="auto" onTimeUpdate={this.trackTime}>

可能重复(DOM节点列表是类似数组的对象)长话短说:有没有办法获得持续时间并播放视频,除非我播放视频onClick。而onClick则有效。那怎么做呢?和以前一样的行为。有时候,我会做一些事情。例如,如果我做了
this.videoRef.current.play(),它将被执行,有时不会。另一方面,
此.videoRef.current.duration
将始终显示NaN。错误:“未捕获(承诺中)DomeException”。您是否在
componentDidUpdate()
中调用了它们?是。我还尝试了
componentDidUpdate(prevProps,prevState){if(prevState.video==this.state.video){console.log(this.videoRef.current.duration);}}
,它只有在我点击播放按钮时才被激活。。。考虑到我事先需要持续时间,这并没有多大帮助。@VeljkoStefanovic这不是
==
,而是
==
componentDidUpdate(prevProps, prevState) {
  if(prevState.video !== this.state.video) { // this.state.video is updated
     // That is the place where you can access into valid this.videoRef
  }
}