React 中的 Super 與 Super(props)的區別

  1. React 中 supersuper(props) 的區別
  2. 在 React 中使用 super() 函式
  3. 在 React 中使用 super(props) 函式
React 中的 Super 與 Super(props)的區別

我們將在 React 中介紹 super()super(props) 並通過示例解釋它們之間的區別。

React 中 supersuper(props) 的區別

在 React 中構建 Web 應用程式時,我們經常需要使用 super()super(props),但有些開發人員不知道它們之間的區別或何時使用哪一個。

在詳細瞭解它們之間的區別之前,我們將首先了解 super()props 是什麼。

當我們需要訪問父類的一些變數時,我們使用 super() 函式。它用於呼叫其父類的建構函式來訪問變數。

另一方面,props 是 React 中的一個特殊關鍵字,用於將資料從一個元件傳遞到另一個元件。props 包含的資料是隻讀的。

因此,來自父元件的資料不能在子元件中更改。

現在,讓我們通過一個例子來理解 super()super(props)。讓我們使用以下命令建立一個新應用程式。

# react
npx create-react-app my-app

在 React 中建立我們的新應用程式後,我們將使用此命令轉到我們的應用程式目錄。

# react
cd my-app

執行應用程式以檢查所有依賴項是否已正確安裝。

# react
npm start

在 React 中使用 super() 函式

我們將建立一個簡單的元件來演示 super() 函式。在 App.js 中,我們將使用 React.Component 擴充套件類 App

在我們的類中,我們將使用 props 定義一個建構函式。在我們的建構函式中,我們將呼叫 super() 並在控制檯中記錄 propsthis.props 以檢查我們得到的輸出。

因此,我們在 App.js 中的程式碼將如下所示。

import React from "react";

class App extends React.Component {
  constructor(props) {
    super();
    console.log(this.props);
    console.log(props);
  }

  render() {
    return <div>Hello {this.props.message}</div>;
  }
}

export default App;

輸出:

react super 示例

如上所示,當我們沒有在 super()console.log(this.props) 中使用 props 時,我們將收到一條未定義的訊息,因為我們在建構函式中使用了 this.props。但是當我們 console.log(props) 時,它給了我們一個正確的訊息,意味著它被定義了。

在 React 中使用 super(props) 函式

讓我們看一下 super(props) 示例。讓我們使用以下命令建立一個新應用程式。

# react
npx create-react-app my-app

在 React 中建立我們的新應用程式後,我們將使用此命令轉到我們的應用程式目錄。

# react
cd my-app

執行應用程式以檢查所有依賴項是否已正確安裝。

# react
npm start

我們將建立一個簡單的元件來演示 super(props) 函式的使用。在 App.js 中,我們將使用 React.Component 擴充套件類 App

在我們的類中,我們將使用 props 定義一個建構函式。在我們的建構函式中,我們將呼叫 super(props) 並在控制檯中記錄 this.props 以檢查我們得到的輸出。

因此,我們在 App.js 中的程式碼將如下所示。

import React from "react";

class App extends React.Component {
  constructor(props) {
    super(props);
    console.log(this.props);
  }

  render() {
    return <div>Hello {this.props.message}</div>;
  }
}

export default App;

輸出:

react super props 示例

如上所示,如果我們想在建構函式中使用 this,我們必須將它傳遞給 super。因此,如果我們想在建構函式中使用 this.props,我們需要將 props 傳遞給 super()

但是如果我們不想使用它,我們只能使用 super()。從上面的例子中,我們還瞭解到,在渲染函式內部,我們是否將 props 傳遞給 super() 並不重要,因為無論我們傳遞 props,this.props 在渲染函式中都是可用的是否為 super()

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn