【问题标题】:Element type is invalid: expected a string (for built-in components) or a class/function?元素类型无效:需要字符串(用于内置组件)还是类/函数?
【发布时间】:2019-07-27 20:48:37
【问题描述】:

我遇到了一个奇怪的 React/Storybook 错误。

我看到的错误是:

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, or you might have mixed up default and named imports.

这是导致错误的代码:

import React from 'react';
import styled from 'styled-components';

class LogoWordMark extends React.PureComponent {
  static Container = styled.div``;

  render() {
    return (
      <LogoWordMark.Container>
        mnkladjkl asdjklas djkkjlsad jklasdjklasd kl
        <a>asdad</a>
      </LogoWordMark.Container>
    );
  }
}

export default LogoWordMark;

奇怪的是,如果我更新一行:

    <a onClick={this.blah}>asdad</a>

然后组件按预期呈现。即使this.blah 没有定义。有人知道这里发生了什么吗?

我正在使用:

"react": "16.8.6",
"@storybook/react": "5.1.7",

【问题讨论】:

  • 尝试用div或>(反应片段)包装内容
  • 环绕容器?还是里面?我都试过了,没有变化
  • 我的意思是&lt;&gt;mnkladjkl asdjklas djkkjlsad jklasdjklasd kl &lt;a&gt;asdad&lt;/a&gt;&lt;/&gt;
  • 没有改变......有这个想法。仍然出错
  • This component works fine. 有其他错误。在那个锚点上弄乱一个道具应该没关系 - 您是否尝试过使用您正在使用的任何构建工具进行重建(以防它只是处于混乱状态)?

标签: reactjs storybook


【解决方案1】:

基于full example you posted

您正在导出 Brand 作为默认值,而不是 importing it as one。将 import { Brand } from "./Brand"; 更改为 import Brand from "./Brand";it should work.


这是错误在最后试图警告的内容:

您可能混淆了默认导入和命名导入。

【讨论】:

    【解决方案2】:

    我的所有导出和导入都是正确的,因此@SamVK 的回答不适用于我收到此错误的原因。

    当使用对另一个组件来说是静态的组件时,似乎会发生此错误。我必须做的修复是重新启动我的开发服务器(NextJS)。 (来自 SamKV 对原始 OP 的评论回复的灵感)

    【讨论】:

    • 我有同样的问题,如果我更改文件中的任何内容,问题就会得到解决,但我没有使用任何静态组件。您能找到导致这种情况发生的根本原因吗?
    猜你喜欢
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2017-12-07
    • 2021-01-23
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    相关资源
    最近更新 更多