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