【问题标题】:Custom component undefined in React NativeReact Native 中未定义的自定义组件
【发布时间】:2017-12-30 20:05:03
【问题描述】:

我在 javascript 文件中创建了一个名为 SimpleButton 的自定义组件:

import React, {
  Text,
  View
} from 'react-native';

export default class SimpleButton extends React.Component{
  render(){
    return (
      <View>
        <Text>Simple Button</Text>
      </View>
    );
  }
}

然后我将它导入到索引 javascript 文件中:

    /**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {
  AppRegistry,
  StyleSheet,
  View
} from 'react-native';

import SimpleButton from './App/Components/SimpleButton';

class ReactNotes extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <SimpleButton/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

AppRegistry.registerComponent('ReactNotes', () => ReactNotes);

最后,在 Android 设备上运行它,它会抛出“Super expression must be null or a function, not undefined”错误。错误导致SimpleButton类声明代码行('export default class SimpleButton extends React.Component'.

我目前使用最新版本的 React Native。我已经搜索了一些解决方案但不起作用。请帮帮我!

【问题讨论】:

    标签: react-native


    【解决方案1】:

    您正在使用 import React from react-native ,它实际上并不存在于 react-native 中。你应该 import React from react 本身 - 相反。我已经修复了下面的 SimpleButton 类。

    import {
      Text,
      View
    } from 'react-native';
    
    import React from 'react';
    
    export default class Test extends React.Component{
      render(){
        return (
          <View>
            <Text>Simple Button</Text>
          </View>
        );
      }
    }
    

    您也可以只添加以下内容 -> import {Component} from 'react'; 然后简单地将此功能用作export default class Test extends Component{...

    (注意这一行替换了我之前提到的import React from 'react'solution)

    希望对你有帮助

    【讨论】:

    • 顺便说一句,您应该在两个文件中实施此修复
    • 我添加了“ import React from 'react'; ”,它现在可以工作了。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 2015-12-10
    • 1970-01-01
    • 2022-11-12
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多