我有一个列表显示视频。我希望当视频消失时,应该暂停它。我在每个Posts
组件中维护暂停状态。
class Posts extends React.PureComponent {
constructor() {
super()
this.state = {
pause: true,
}
return(){
<Video
pause={this.state.pause}
//other props
/>
}
}
我正在使用react-native-video
。
我尝试使用Flatlist
的onViewableItemsChanged
Prop,但不会改变状态。
我尝试过。但这似乎对我不起作用。
我应该如何继续?
这是使用React-Native-InviewPort的解决方案。此依赖关系只是一个单个索引文件,该文件包含一个组件,该组件在视图中查看时具有回调。它可以轻松修改以适合您的需求。
我已经构建了一个非常简单的应用程序,该应用程序具有lactlast列表。lantlist中的第11个项目是视频。这应该意味着当应用程序呈现时,视频就在屏幕上,以免播放Viddeo,一旦视频完全进入视口,就应该开始播放。
App.js
import * as React from 'react';
import { Text, View, StyleSheet, FlatList } from 'react-native';
import Constants from 'expo-constants';
import VideoPlayer from './VideoPlayer';
export default class App extends React.Component {
state = {
data: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
}
renderItem = ({item, index}) => {
if (index === 10) {
return <VideoPlayer />
} else {
return (
<View style={{height: 100, backgroundColor: '#336699', justifyContent: 'center', alignItems: 'center'}}>
<Text>{index}</Text>
</View>
)
}
}
keyExtractor = (item, index) => `${index}`;
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
}
});
VideoPlayer.js
这是包含视频组件的组件。该视频包裹在具有回调功能的InViewPort
组件中。当它包围的组件为完全时,回调将返回true,而当视口不完全在视口中时,回调返回。回调调用 this.handlePlaying
,依次调用this.playVideo
或this.pauseVideo
,具体取决于布尔值。
import React, {Component} from 'react';
import { View, StyleSheet } from 'react-native';
import { Video } from 'expo-av';
import InViewPort from './InViewPort';
//import InViewPort from 'react-native-inviewport; // this wouldn't work in the snack so I just copied the file and added it manually.
export default class VideoPlayer extends React.Component {
pauseVideo = () => {
if(this.video) {
this.video.pauseAsync();
}
}
playVideo = () => {
if(this.video) {
this.video.playAsync();
}
}
handlePlaying = (isVisible) => {
isVisible ? this.playVideo() : this.pauseVideo();
}
render() {
return (
<View style={styles.container}>
<InViewPort onChange={this.handlePlaying}>
<Video
ref={ref => {this.video = ref}}
source={{ uri: 'http://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4' }}
rate={1.0}
volume={1.0}
isMuted={false}
resizeMode="cover"
shouldPlay
style={{ width: 300, height: 300 }}
/>
</InViewPort>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center'
}
});
这是一个零食,显示它可以正常工作https://snack.expo.io/@andypandy/video-only-only-playing-when-in-in-viewport
我应该指出的是,如果视频不是完全在视口中,则不会播放。我确定可以对react-native-inviewport
进行一些调整,以便如果您想要的话,它会在视频中部分播放视频,也许是将视频的高度传递给InViewPort
组件。
这就是我简单地做技巧的方式在我的卡组件中,有视频
<Video ...
paused={currentIndex !== currentVisibleIndex}
/>
CurrentIndex和CurrentVisibleIndex均来自 flatlist parent
的组件我的flatlist通过 RenderItem索引作为CurrentIndex
<FlatList
data={[...]}
renderItem={({ item, index }) => (
<GalleryCard
{...item}
currentIndex={index}
currentVisibleIndex={currentVisibleIndex}
/>
)}
onViewableItemsChanged={this.onViewableItemsChanged}
viewabilityConfig={{
viewAreaCoveragePercentThreshold: 90
}}
最后,我的这是如何计算 CurrentVisibleIndex 请确保阅读可透视性config
onViewableItemsChanged = ({ viewableItems, changed }) => {
if (viewableItems && viewableItems.length > 0) {
this.setState({ currentVisibleIndex: viewableItems[0].index });
}
};
请让我知道这是否有帮助
我最终使用redux做到了这一点。不确定是否是正确的方式。
home.js
_renderItem = ({item, index}) => <Posts item={item} />
viewableItemsChanged = (props) => {
let {changed} = props;
let changedPostArray = [];
changed.map((v,i) => {
let {isViewable, item} = v;
if(!isViewable) {
let {post_id, type} = item;
if(type === 1)
changedPostArray.push(post_id);
}
});
if(changedPostArray.length != 0)
this.props.sendPostToPause(changedPostArray);
}
render() {
return(
<View style={{flex: 1}} >
<FlatList
ref={(ref) => this.homeList = ref}
refreshing={this.state.refreshing}
onRefresh={async () => {
await this.setState({refreshing: true, postsId: [0], radiusId: 0, followingId: 0});
this.getPosts();
}}
onEndReached={async () => {
if(!this.state.isEnd) {
await this.setState({isPaginate: true})
this.getPosts()
}
}}
onEndReachedThreshold={0.2}
removeClippedSubviews={true}
contentContainerStyle={{paddingBottom: 80}}
data={this.state.followersRes}
renderItem={this._renderItem}
viewabilityConfig={this.viewabilityConfig}
onViewableItemsChanged={this.viewableItemsChanged}
/>
</View>
<Footer callback={this.scrollToTopAndRefresh} />
</View>
)
}
export default connect(null, {sendPostToPause})(Home);
posts.js
class Posts extends React.PureComponent {
constructor(){
super()
this.state: {
pause: false
}
}
componentDidUpdate(prevProps) {
if(prevProps != this.props) {
this.props.postIdArray.map((v) => {
if(v === prevProps.item.post_id) {
this.setState({pause: true})
}
})
}
}
render(){
return(
<Video
pause={this.state.pause}
//Other props
/>
)
}
}
const mapStateToProps = (state) => {
const {postId} = state.reducers;
return {
postIdArray: postId
}
}
export default connect(mapStateToProps, {sendPostToPause})(withNavigation(Posts));
每当viewableItemsChanged
是触发器时,我都在数组中添加了更改的帖子ID,并用帖子ID数组调用操作。在Posts
组件中,我正在检查帖子ID是否匹配,如果是的,我将暂停状态设置为true。