React技巧之導入組件

  • 2022 年 6 月 30 日
  • 筆記

正文從這開始~

總覽

在React中,從其他文件中導入組件:

  1. A文件中導出組件。比如說,export function Button() {}
  2. B文件中導入組件。比如說,import {Button} from './another-file'
  3. B文件中使用導入的組件。

命名導入導出

下面的例子是從一個名為another-file.js的文件中導入組件。

// 👇️ named export
export function BigButton() {
  return (
    <button
      style={{padding: '2rem 1rem'}}
      onClick={() => console.log('big button')}
    >
      Big button
    </button>
  );
}

// 👇️ named export
export const SmallButton = () => {
  return (
    <button onClick={() => console.log('small button')}>Small button</button>
  );
};

下面是我們如何從一個名為App.js文件中導入組件。

// 👇️ named import
import {BigButton, SmallButton} from './another-file';

export default function App() {
  return (
    <div>
      <BigButton />

      <hr />

      <SmallButton />
    </div>
  );
}

如有必要,請確保當前路徑指向another-file.js模塊。上面的例子假設another-file.jsApp.js位於相同的目錄下。

舉例來說,如果another-file.js位於上層目錄,你必須這樣導入:import {BigButton} from '../another-file'

在導入組件時,我們使用大括號包裹組件名稱。這被稱為命名導入。

import/export語法被稱為JavaScript模塊。為了能夠從不同的文件中導入一個組件,必須使用命名的或默認的導出方式將其導出。上述例子使用了命名導出和導入。

命名和默認導入導出的主要不同之處在於,在每個文件中,你可以有多個命名導出,但只能有一個默認導出。

默認導入導出

讓我們看一個例子,看看我們如何導入一個使用默認導出的組件。

// 👇️ default export
export default function BigButton() {
  return (
    <button
      style={{padding: '2rem 1rem'}}
      onClick={() => console.log('big button')}
    >
      Big button
    </button>
  );
}

很重要:如果你導出一個變量(或者箭頭函數)作為默認導出,你必須先聲明再導出。你不能在同一行內聲明變量同時默認導出變量。

const BigButton = () =>  {
  return (
    <button
      style={{padding: '2rem 1rem'}}
      onClick={() => console.log('big button')}
    >
      Big button
    </button>
  );
}

// 👇️ default export
export default BigButton;

下面是如何使用默認導入來導入組件。

// 👇️ default import
import BigButton from './another-file';

export default function App() {
  return (
    <div>
      <BigButton />
    </div>
  );
}

當導入組件時,我們也可以使用不同的名字,比如Foo

// 👇️ default import
import Foo from './another-file';

export default function App() {
  return (
    <div>
      <Foo />
    </div>
  );
}

這樣也會生效,但會令人疑惑,因此應該避免。

根據我的經驗,大多數現實世界的代碼庫只使用命名的導出和導入,因為它們更容易利用你的IDE進行自動完成和自動導入。 你也不必考慮哪些成員是用默認導出或命名導出的。

混合導入導出

你也可以混合匹配,下面示例的文件使用了默認導出和命名導出。

// 👇️ default export
export default function BigButton() {
  return (
    <button
      style={{padding: '2rem 1rem'}}
      onClick={() => console.log('big button')}
    >
      Big button
    </button>
  );
}

// 👇️ named export
export const SmallButton = () => {
  return (
    <button onClick={() => console.log('small button')}>Small button</button>
  );
};

下面是如何導入這兩個組件。

// 👇️ default and named imports
import BigButton, {SmallButton} from './another-file';

export default function App() {
  return (
    <div>
      <BigButton />

      <hr />

      <SmallButton />
    </div>
  );
}

我們使用默認導入來導入BigButton組件,使用命名導入來導入SmallButton組件。

請注意,每個文件只能有一個默認導出,但你可以根據需要有多個命名導出。