首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >react-native- video :如何在点击按钮时加载下一个视频?

react-native- video :如何在点击按钮时加载下一个视频?
EN

Stack Overflow用户
提问于 2018-12-06 06:14:48
回答 1查看 3.3K关注 0票数 2

我有一个名为VIDEOS [ ]的视频数组,当我单击一个按钮时,它的索引递增+1。该按钮触发一个函数nextVideo()

我使用的是react-native-video

如何让播放器播放下一个视频?所以

代码语言:javascript
运行
复制
<Video source={{uri: VIDEOS[currentVideo]}} /> 

需要使用名为currentVideo的更新计数器重新加载App.js中的render()函数。

代码如下:

代码语言:javascript
运行
复制
constructor(props) {
    super(props);

    //Video properties
    this.state = {
        repeat: false,
        paused: false,
    };
    //VIDEO index variable
    global.currentVideo = 0;
 }

  nextVideo() { 
    //Skip video when button is pressed to next video in list
    if (global.currentVideo != VIDEOS.length-1)
    {
        global.currentVideo = global.currentVideo + 1;
    }
    else
    {
        global.currentVideo = 0;
    }
   }

 render() {
    return (
        <View style={styles.container}>
          <View style={styles.video}>
           <Video 
            source={{uri: VIDEOS[global.currentVideo]}}
            ref={(ref) => {this._player = ref}}
            style={styles.video}
           />    
          </View>
          <View style={styles.button}>
            <Button
              onPress={this.nextVideo}
            />
          </View>
        </View>
  );
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-06 07:15:29

一种在需要时触发重新渲染的方法是将视频索引变量放入组件的状态中,并在单击时更新它。

下面是一些带有修改和注释的代码:

代码语言:javascript
运行
复制
constructor(props) {
    super(props);

    //Video properties
    this.state = {
        repeat: false,
        paused: false,
        currentVideo: 0, // <-- moved it to state
    };

    this.nextVideo = this.nextVideo.bind(this); //<-- bind method, since we're accessing this
 }

  nextVideo() { 
    //Skip video when button is pressed to next video in list
    if (this.state.currentVideo != VIDEOS.length-1)
    {
        this.setState({currentVideo: this.state.currentVideo + 1}); //<-- use setState instead of assignment to update
    }
    else
    {
        this.setState({currentVideo: 0}); //<-- use setState instead of assignment to update
    }
   }

 render() {
    return (
        <View style={styles.container}>
          <View style={styles.video}>
           <Video 
            source={{uri: VIDEOS[this.state.currentVideo]}}
            ref={(ref) => {this._player = ref}}
            style={styles.video}
           />    
          </View>
          <View style={styles.button}>
            <Button
              onPress={this.nextVideo}
            />
          </View>
        </View>
  );
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53641571

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档