![](/img/trans.png)
[英]How can I redirect to another component in react and pass the state that I set in the previous component?
[英]How can I set the state of a component on video end in react?
在我的組件我有一個componentDidUpdate
功能,我播放視頻並在該視頻中,我設定的video.onended
事件作為注意到這里
目前,我的代碼如下所示:
componentDidUpdate: function() {
if(this.state.showVideo){
this.refs.homeVideo.play();
// Triggering event on video end
let homeVideo = document.getElementById("homeVideo");
homeVideo.onended = function(){
console.log(this.state);
this.setState({ showVideo: !this.state.showVideo });
}
}
}
我現在的問題是onstate函數中未定義this.state,setState也未定義,這使我無法在react中更新組件的狀態,以便我可以在視頻播放器結束時關閉它。
處理此問題的適當反應方式是什么?
這是因為每個新函數都定義了自己的this
值。
您可以執行以下操作:
var self = this;
homeVideo.onended = function(){
console.log(self.state);
self.setState({ showVideo: !self.state.showVideo });
}
或者更好的是,如果您使用的是ES6,請使用箭頭功能:
homeVideo.onended = () => {
console.log(this.state);
this.setState({ showVideo: !this.state.showVideo });
}
箭頭函數按詞法綁定this
值。
您不需要document.getElementById。
嘗試將代碼更新為此:
componentDidUpdate: function() {
var self = this;
if(this.state.showVideo){
let video = this.refs.homeVideo;
video.play();
video.onended = function(){
console.log(self.state);
self.setState({ showVideo: !self.state.showVideo });
}
}
}
JSfiddle示例https://jsfiddle.net/ntfjncuf/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.