代码之家  ›  专栏  ›  技术社区  ›  Karol

组件内部的组件

  •  0
  • Karol  · 技术社区  · 2 年前

    我正在与React合作。js公司

    我想在应用程序组件(app.js)内部使用一个组件x,它位于索引内部。js。

    它不起作用。 **

    Error
    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.
    Check the render method of `App`.
    

    **

    指数js公司

        import { StrictMode } from "react";
    import { createRoot } from "react-dom/client";
    
    import App from "./App";
    
    const rootElement = document.getElementById("root");
    const root = createRoot(rootElement);
    
    root.render(
      <StrictMode>
        <App />
      </StrictMode>
    );
    

    import "./styles.css";
    import {SubComponent} from "./components/Subcomponent";
    
    export default function App() {
      return (
        <SubComponent/>
      );
    }
    

    子组件

    const HelloWorld = ()=>{ return(<p>Hello World !</p>)}
    export default HelloWorld();
    

    子组件文件夹为:

    enter image description here

    1 回复  |  直到 2 年前
        1
  •  0
  •   CertainPerformance    2 年前

    您的子组件:

    • 需要导出与应用中导入的名称相同的名称-在两个位置使用相同名称的导入/导出,或在两个位置使用默认导入/导出。(您当前正在导入命名的 SubComponent 但默认导出)
    • 需要导出 组成部分 ,这是一个函数,因此可以使用 React.createElement 应用程序内部。不要自己调用函数。

    应用程序。js公司

    import {SubComponent} from "./components/Subcomponent";
    

    子组件

    export const SubComponent = () => {
      return(<p>Hello World !</p>)
    };