【问题标题】:How can I properly import a Component into my Navigator in React Native?如何在 React Native 中将组件正确导入到我的导航器中?
【发布时间】:2016-03-07 17:14:17
【问题描述】:

我在另一个文件夹中有一个名为 EnterName 的组件,我想在我的 Navigator 中使用我的 index.ios 文件。当我将EnterName 放在同一个文件中时,我没有遇到任何问题,但是当我尝试从另一个文件中导入它时,我得到:

Element type is invalid: expected a string (for built-in components 
or a class/function (for composite components) but got: undefined. 
Check the render method of `Navigator`

我尝试了两种不同的方法来导入 EnterName 组件,但都不起作用:

import {EnterName} from './App/Components/EnterName'; var EnterName = require('./App/Components/EnterName');

以下是一些使用 Navigator 并尝试使用来自另一个文件夹的组件 EnterName 的文本(当在同一文件中声明 EnterName 时有效)。

  render() {
    return (
      <Navigator
        initialRoute={{name: 'Name entry', index: 0}}
        renderScene={(route, navigator) =>
            <EnterName
              name={route.name}
              onForward={() => {
                var nextIndex = route.index + 1;
                navigator.push({
                  name: 'Scene ' + nextIndex,
                  index: nextIndex,
                });
              }}
              onBack={() => {
                if (route.index > 0) {
                  navigator.pop();
                }
              }}
            />
        }
      />
    );
  }
}

而且,如果您想查看 EnterName 文件,它就在这里:

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

class EnterName extends Component {
  render() {
    return (
      <View style={styles.center}>
        <View style={styles.flowRight}>
          <TextInput style={styles.inputName}
            placeholder="Enter your name"
            textAlign="center"
            onChangeText={(text) => this.setState({text})}
            //value={this.state.text}
          />

          <TouchableHighlight style={styles.button}
          underlayColor='#99d9f4'>
          <Text style={styles.buttonText}> Go </Text>
        </TouchableHighlight>
        </View>
      </View>
      )
  }
}
// The stylesheet is here, and then below it I have:
module.export = EnterName;

你能帮我弄清楚如何模块化我的代码吗?

编辑:我只是忘记了 module.exports 末尾的“s”。似乎 export default class _classname extends Component { 是要走的路。

【问题讨论】:

  • 试试export default class EnterName extends Component
  • 我尝试了使用和不使用module.export = EnterName,然后在 index.ios 类中导入了我的两种变体。没用。
  • 我总是使用module.exports = EnterName,我不太了解 JavaScript 以及什么是有效的,但这会是问题吗?

标签: javascript import reactjs module react-native


【解决方案1】:

您是否错过了module.export 末尾的“s”。应该是module.exports。在这种情况下,导入应该是

import EnterName from './App/Components/EnterName

你也可以使用 module.exports 来代替

export default class EnterName extends Component

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/import

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    相关资源
    最近更新 更多