当我在导航堆栈上使用this.props.navigation.push时,我的视频将继续在后台播放。当我离开时,是否可以暂停或停止视频?
<VideoPlayer
videoProps={{
shouldPlay: true,
resizeMode: Video.RESIZE_MODE_CONTAIN,
isMuted: false,
source: {
uri: this.props.navigation.state.params.video,
},
}}
isPortrait
playFromPositionMillis={0}
showFullscreenButton
switchToLandscape={() =>
ScreenOrientation.allowAsync(ScreenOrientation.Orientation.LANDSCAPE)
}
switchToPortrait={() =>
ScreenOrientation.allowAsync(ScreenOrientation.Orientation.PORTRAIT)
}
/>
让我知道是否需要进一步详细说明。
答案 0 :(得分:0)
使用react-navigation
时,可以在导航生命周期事件上使用侦听器。 https://reactnavigation.org/docs/en/navigation-prop.html#addlistener-subscribe-to-updates-to-navigation-lifecycle
您可以订阅四个活动:
willFocus
-屏幕将聚焦didFocus
-屏幕聚焦(如果有过渡,则过渡完成)willBlur
-屏幕将无法对焦didBlur
-屏幕未聚焦(如果存在过渡,则过渡完成)
您可以根据需要订阅任意数量的内容。这是使用willBlur
的示例。您可以轻松地将其复制为所需的全部内容。
componentDidMount () {
// add listener
this.willBlurSubscription = this.props.navigation.addListener('willBlur', this.willBlurAction);
}
componentWillUmount () {
// remove listener
this.willBlurSubscription.remove();
}
willBlurAction = (payload) => {
// do things here when the screen blurs
}
VideoPlayer
VideoPlayer docs与ref
Video docs并没有公开相同的Video
函数,但是您可以使用. _playbackInstance
来获得它们。 。因此,您可以执行以下操作:
<VideoPlayer
ref={ref => {this.videoplayer = ref}}
// other props
/>
然后您可以在didBlurAction
函数中执行类似的操作
didBlurAction = (payload) => {
if (this.videoplayer) {
this.videoplayer._playbackInstance.pauseAsync();
}
}
我制作了一种小吃,证明它能正常工作。在小吃中,您可以在使用Video
或VideoPlayer
之间切换。当您导航到下一个屏幕时,视频暂停。还有两个按钮可让您pause
或play
视频。
https://snack.expo.io/@andypandy/video-example