【问题标题】:react-native-video: how to load next video on clicking a button?react-native-video:如何在单击按钮时加载下一个视频?
【发布时间】:2018-12-05 22:14:47
【问题描述】:

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

我正在使用 react-native-video

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

<Video source={{uri: VIDEOS[currentVideo]}} /> 

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

代码如下:

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>
  );

【问题讨论】:

  • 嗨,欢迎来到 SO。你能展示更多你的代码吗?
  • 是的,如果您能展示外部组件以及如何增加计数器,那就太好了。
  • 刚刚用一些代码更新了 OP
  • 理想情况下,在 nextVideo() 函数的末尾,应该有一种方法可以启动视频播放器以使用更新后的计数器。

标签: reactjs react-native button video


【解决方案1】:

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

这是你的一些修改和 cmets 的代码:

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>
  );

【讨论】:

  • 天才!我之前尝试过 setState,但我认为我缺少的部分确实是与 nextVideo() 的绑定。所以出于兴趣,'render()' 函数是否总是刷新?我只是想知道我的 如何锁定到更新的“currentVideo”索引号。谢谢!
  • 只要组件的状态发生变化,就会触发重新渲染。通过阅读有关状态和生命周期的 react 文档部分,您可以更好地了解正在发生的事情:reactjs.org/docs/…
最近更新 更多