關於RN組件的導出export和export default

一般我們在定義了一個組件之後,爲了複用,需要將它導出以提供給其他頁面使用。

組件導出的關鍵字是

exprot default

沒有加default時,例如:

export class Template{}

當然,你可以在單個js文件裏聲明多個組件,例如Templates.js

export class Template{}
export class AnotherTemplate{}

這樣在其他文件引用時,需要使用{}符號且組件名稱必修和class名稱一樣,像這樣子:

import {Template,AnotherTemplate} from './components/Templates';

而加default時,例如:

export default class Template{}

然後在其他文件引用,像這樣子:

import Template from './components/Templates';

你也可以爲這個組件另起一個別名,像這樣子:

import TheTemplate from './components/Templates';

但是每個文件裏只能有個default組件,可以包含其他非default組件:

export default class Template{}
export class AnotherTemplate{}

然後引用的時候,如下:

import Template,{AnotherTemplate} from './components/Templates';

總結

  • 有default和沒有default的區別在於:有default在引用時可以自定義名稱,而沒有default時需要使用{}括起來且名稱必修和class名稱一致
  • 每個文件裏只能有一個default組件,但可以有多個非default組件
發佈了106 篇原創文章 · 獲贊 382 · 訪問量 118萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章