React Native如何在WebView中控制播放/暂停视频

时间:2020-03-19 03:28:33

标签: react-native webview html5-video

我正在尝试通过React Native在WebView中播放和暂停视频。
但是当this.state.shouldPlay变为true时,下面注入的JavaScript不起作用。

injectedJavaScript=
{`document.getElementsByTagName("video")[0].play();`}

请建议如何从React Native的WebView中控制视频。
由于性能问题,无法使用react-native-video。

import * as React from 'react';
import { Component, useState, useEffect  } from 'react';
import { Text, View, StyleSheet, Image, TouchableOpacity} from 'react-native';
import {WebView} from 'react-native-webview';

export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      shouldPlay: false, // not play at default
    }
  }

  _handlePlayAndPause = () => {
    if (this.state.shouldPlay == false) {
      this.setState({shouldPlay: true });
    } else {
      this.setState({shouldPlay: false });
    };

  render() {
    const {shouldPlay } = this.state;

    return (
        <View style={styles.container}>
          { shouldPlay ? 
            <View>
              <WebView
                source={{ uri: www.url.com/sample.mp4 }}
                javaScriptEnabled = {true}
                injectedJavaScript=
                  {`document.getElementsByTagName("video")[0].play();`}
              />
            </View>
          :
            <View>
              <WebView
                source={{ uri: www.url.com/sample.mp4 }}
                javaScriptEnabled = {true}
                injectedJavaScript=
                  {`document.getElementsByTagName("video")[0].pause();`}
              />
            </View>
          }

          { shouldPlay ?
            <View>
              <TouchableOpacity onPress={ this._handlePlayAndPause } >  
                  <Ionicons name="ios-pause"/>
              </TouchableOpacity>
            </View>
          :
            <View>
              <TouchableOpacity onPress={ this._handlePlayAndPause } > 
                  <Ionicons name="ios-play-circle"/>
              </TouchableOpacity>
            </View>              
          }
        </View>
    )  
  }

}

谢谢。

0 个答案:

没有答案