首页 > 解决方案 > 期望一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:

问题描述

当我导出以下组件时,为什么会出现错误Expected a string (for built-in components) or a class/function (for composite components) but got: <Fragment />. Did you accidentally export a JSX literal instead of a component?Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

const MyComponent = (
    <>
        <h1>Hello</h1>
        <div>Lorem Ipsum</div>
    </>
)
export default MyComponent

这个问题与链接的问题不同。它与某人可能会发现和谷歌搜索的特定错误有关。

标签: javascriptreactjs

解决方案


解决办法是把组件改成函数:

const MyComponent = () => (
    <>
        <h1>Hello</h1>
        <div>Lorem Ipsum</div>
    </>
)
export default MyComponent

如果您使用的是打字稿,则返回类型为React.ReactElement


推荐阅读