stk*_*flw 221 javascript ecmascript-6
该组件确实有效:
export class Template extends React.Component {
render() {
return (
<div> component </div>
);
}
};
export default Template;
Run Code Online (Sandbox Code Playgroud)
如果我删除最后一行,它不起作用.
Uncaught TypeError: Cannot read property 'toUpperCase' of undefined
Run Code Online (Sandbox Code Playgroud)
我想,我不明白es6语法中的一些东西.是不是必须导出没有"默认"的标志?
Jed*_*rds 545
无需出口default
就是"命名出口".您可以在单个文件中具有多个命名导出.所以,如果你这样做,
class Template {}
class AnotherTemplate {}
export { Template, AnotherTemplate }
Run Code Online (Sandbox Code Playgroud)
那么你必须使用他们的确切名称导入这些导出.因此,要在另一个文件中使用这些组件,您必须这样做,
import {Template, AnotherTemplate} from './components/templates'
Run Code Online (Sandbox Code Playgroud)
或者,如果您default
像这样导出为导出,
export default class Template {}
Run Code Online (Sandbox Code Playgroud)
然后在另一个文件中导入默认导出而不使用{}
,像这样,
import Template from './components/templates'
Run Code Online (Sandbox Code Playgroud)
每个文件只能有一个默认导出.在React中,从文件中导出一个组件是一种约定,并将其导出为默认导出.
您可以在导入时自由重命名默认导出,
import TheTemplate from './components/templates'
Run Code Online (Sandbox Code Playgroud)
您可以同时导入默认导出和命名导出,
import Template,{AnotherTemplate} from './components/templates'
Run Code Online (Sandbox Code Playgroud)
在导入和导出时添加 { }:
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 };
Run Code Online (Sandbox Code Playgroud)
// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";
export default function App() {
return (
<>
<strong>
<DefaultExport />
</strong>
<br />
<Export1 />
<br />
<Export2 />
</>
);
}
Run Code Online (Sandbox Code Playgroud)
??工作沙箱:https : //codesandbox.io/s/export-import-example-react-jl839 ?fontsize =14&hidenavigation=1&theme=dark
归档时间: |
|
查看次数: |
162304 次 |
最近记录: |