首页 > 解决方案 > react-native-video 示例抛出“TypeError:undefined”错误

问题描述

我对本机反应很陌生。我正在尝试制作一个嵌入了 youtube 视频的应用程序。我正在尝试这个 repo 的示例,但它在我的项目中崩溃了。

这是我的完整代码。崩溃在它们被抛出的地方被评论。我不明白我做错了什么。

我正在使用 webstorm 并且我很确定我已经安装了该软件包并使用以下命令将其链接:

npm install --save react-native-video

react-native 链接 react-native-video

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
} from 'react-native';
import {
  Header,
  LearnMoreLinks,
  Colors,
  DebugInstructions,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import Video from 'react-native-video';

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={styles.scrollView}>
          <View style={styles.body}>
            <View>
              <Video source={{uri: "https://www.youtube.com/watch?v=83mkGuGLNZg"}}
                 ref={(ref) => {
                   this.player = ref //Crash with TypeError:undefined is not an object
                 }}                                      // Store reference
                 onBuffer={this.onBuffer}                //Crash with TypeError:undefined is not an object
                 onError={this.videoError}               //Crash with TypeError:undefined is not an object
                 style={styles.backgroundVideo}
              />
            </View>
          </View>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.lighter,
  },
  engine: {
    position: 'absolute',
    right: 0,
  },
  body: {
    backgroundColor: Colors.white,
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: Colors.black,
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
    color: Colors.dark,
  },
  highlight: {
    fontWeight: '700',
  },
  footer: {
    color: Colors.dark,
    fontSize: 12,
    fontWeight: '600',
    padding: 4,
    paddingRight: 12,
    textAlign: 'right',
  },
  backgroundVideo: {
    position: 'absolute',
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
  },
});

export default App;

标签: androidreactjsreact-native

解决方案


问题是你的this陈述。它指的是你所处的功能。

当使用严格模式时,函数中的 'this' 将引用它的显式值,如果 'this' 没有被显式设置,那么 'this' 将是未定义的。

因此,您必须bind使用this.player=this.player.bind(this).

有关更多信息,您可以查看此处


推荐阅读