ios - React Native 无状态组件说未定义

标签 ios reactjs react-native

我正在尝试使用 React Native 创建一个组件,如下所示:

export class IndicatorOverlay extends Component {
  render() {
    return (
      <View>
        <Text>text</Text>
      </View>
    );
  }
};

上面的方法有效,但是当我尝试使其无状态时......

export default ({ text = 'text' }) => {
  return (
    <View>
      <Text>{text}</Text>
    </View>
  );
};

我收到以下错误:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

我确信我错过了一些基本的东西,但我就是看不到它。我在 React Web 应用程序中使用了类似的无状态组件,效果很好。

使用react 16.0.0-alpha.6和react-native 0.43.2,我在iPhone模拟器中看到这个错误。

希望有人能帮忙:)

最佳答案

这可能是因为第一个示例是命名导出,而第二个示例是默认导出,因此导入它们的方式不同。

假设您像这样导入模块:

import { IndicatorOverlay } from 'IndicatorOverlay';

你有两个选择。要么:

1) 更改导入模块的方式(因为无状态组件现在是默认导出):

import IndicatorOverlay from 'IndicatorOverlay';

2)保持导入完整,但将无状态组件重构为如下所示:

export const IndicatorOverlay = ({text = 'text'}) => {
  return (
    <View>
      <Text>{text}</Text>
    </View>
  );
};

顺便说一句,你可以让它更干燥:

export const IndicatorOverlay = ({ text = 'text' }) => (
  <View>
    <Text>{text}</Text>
  </View>
);

您可以在 MDN 上阅读有关导入和导出的更多信息:

关于ios - React Native 无状态组件说未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43409982/

相关文章:

javascript - react native , 'is not usable as a native method argument'

javascript - map 内匿名函数内的方法未定义

javascript - 我该如何解决这个问题 : "node_modules/expo/AppEntry.js: [BABEL]"?

ios - Xcode如何强制重建依赖框架目标

iOS 编程菜鸟,需要帮助修复错误消息

javascript - 数组对象的 Typescript 接口(interface)

javascript - 是否可以初始化一次 redux 存储并在多个页面中使用?

ios - 添加照片到 MWPhotoBrowser

ios - “字节”不可用 : use withUnsafeBytes instead

reactjs - 无法从 "./aws-exports"解析 "App.js"