【问题标题】:React Native Stateless component saying undefinedReact Native Stateless 组件说未定义
【发布时间】:2017-04-14 19:39:27
【问题描述】:

我正在尝试像这样使用 React Native 创建一个组件:

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

上述方法有效,但是当我尝试像这样使其无状态时......

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

我收到以下错误:

元素类型无效:应为字符串(用于内置组件) 或类/函数(用于复合组件)但得到:未定义。你 可能忘记从定义它的文件中导出您的组件。

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

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

希望有人可以提供帮助:)

【问题讨论】:

  • 我遇到过类似的行为。但是尝试const IndicatorOverlay = (...) =&gt; {...} 然后export default IndicatorOverlay。它应该可以工作。

标签: ios reactjs react-native


【解决方案1】:

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

假设您像这样导入模块:

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 上阅读有关导入和导出的更多信息:

【讨论】:

  • 太棒了!谢谢你。 +1 让它更干一点...... :)
猜你喜欢
  • 2017-12-30
  • 2022-11-12
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2021-09-15
  • 2016-09-26
  • 2022-01-21
相关资源
最近更新 更多