为什么 es6 react 组件仅适用于“导出默认值”?

2022-08-30 00:20:32

此组件可以工作:

export class Template extends React.Component {
    render() {
        return (
            <div> component </div>
        );
    }
};
export default Template;

如果我删除最后一行,它不起作用。

Uncaught TypeError: Cannot read property 'toUpperCase' of undefined

我想,我不理解es6语法中的某些东西。难道它不必在没有符号“默认”的情况下导出吗?


答案 1

不导出意味着它是“命名导出”。您可以在单个文件中有多个命名导出。所以如果你这样做,default

class Template {}
class AnotherTemplate {}

export { Template, AnotherTemplate }

然后,您必须使用其确切名称导入这些导出。因此,要在另一个文件中使用这些组件,您必须这样做,

import {Template, AnotherTemplate} from './components/templates'

或者,如果您像这样导出,default

export default class Template {}

然后在另一个文件中导入默认导出,而不使用 ,如下所示,{}

import Template from './components/templates'

每个文件只能有一个默认导出。在 React 中,约定是从文件中导出一个组件,而导出它是默认导出。

您可以在导入时自由重命名默认导出,

import TheTemplate from './components/templates'

您可以同时导入默认导出和命名导出,

import Template,{AnotherTemplate} from './components/templates'

答案 2

导入和导出时添加 { }:|export { ... };import { ... } from './Template';

导出import { ... } from './Template'

导出默认import ... from './Template'


下面是一个工作示例:

// ExportExample.js
import React from "react";

function DefaultExport() {
  return "This is the default export";
}

function Export1() {
  return "Export without default 1";
}

function Export2() {
  return "Export without default 2";
}

export default DefaultExport;
export { Export1, Export2 };

// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";

export default function App() {
  return (
    <>
      <strong>
        <DefaultExport />
      </strong>
      <br />
      <Export1 />
      <br />
      <Export2 />
    </>
  );
}

⚡️要玩的工作沙盒:https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark