📜  什么时候在 ReactJS 中使用类组件而不是函数组件?

📅  最后修改于: 2022-05-13 01:56:15.393000             🧑  作者: Mango

什么时候在 ReactJS 中使用类组件而不是函数组件?

简介:组件是在 React 中创建用户界面的构建块。它们使我们能够开发可重用且独立的相互链接的组件,这些组件共同构成了整个 Web 界面。 React 有 2 种不同类型的组件:

句法:

类组件——使用 ES2015 类模板创建的组件称为类组件。

class FirstComponent extends React.Component {
    render() {
        return 

This is a class component!

; } }

函数组件——使用 JavaScript函数语法创建的组件是函数组件。

function anotherComponent(props) {
   return 

This is a function component!

; }

现在我们知道了组件是什么,让我们尝试了解什么时候应该使用类或函数组件。我们首先需要了解组件状态的概念。你可以参考这篇文章来更好地理解 React 状态。

在类组件的情况下,当组件的状态发生变化时,会调用渲染方法。然而,每当 props 改变时,函数组件都会渲染界面。

虽然我们应该更喜欢在大多数情况下使用函数组件,因为 React 还允许在 React 16.8 及更高版本中通过使用 useState 挂钩将状态与函数组件一起使用,这也是 Meta(Facebook 应用程序)本身推荐的。但是对于较旧的 React 版本,我们可以使用依赖于组件状态的类组件。

类组件与函数组件:

Class Components

Function Components

Class components need to extend the component from “React.Component” and create a render function that returns the required element.Functional components are like normal functions which take “props” as the argument and return the required element.
They are also known as stateful components.They are also known as stateless components.
They implement logic and the state of the component.They accept some kind of data and display it in the UI.
Lifecycle methods can be used inside them.Lifecycle methods cannot be used inside them.

Format of Hooks inside class components:

Format of Hooks inside function components:

It needs to store state therefore constructors are used.Constructors are not used in it.
It has to have a “render()” method inside that.It does not require a render method.

示例 1:这是一个基本示例,将说明类组件和功能组件:

类组件:

Javascript
constructor(props) {
    super(props);
    this.state = { color: ‘ ‘ }
}


Javascript
const [color,SetColor]= React.useState('')


Javascript
import React from "react";
  
class ClassComponent extends React.Component {
    render() {
        return 

It's a class component!

;     } }    export default ClassComponent;


Javascript
import React from "react";
  
const FunctionComponent = () => {
    return 

It's a function component!

; };    export default FunctionComponent;


输出:

类组件示例

函数组件:

Javascript

import React from "react";
  
class Something extends React.Component {
    render() {
        return 

A Computer Science          Portal For Geeks

;     } }    class ClassComponent extends React.Component {     render() {         return ;     } }    export default ClassComponent;

输出:

函数组件示例

示例 2:这是类组件和功能组件的另一个示例:

类组件:

Javascript

import React from "react";
  
const Something = () => {
    return 

It's a better function      component!

; };    const FunctionComponent = () => {     return ; };    export default FunctionComponent;

输出:

类组件示例

函数组件:

Javascript

import React from "react";
  
const FunctionComponent = () => {
    return 

It's a function component!

; };    export default FunctionComponent;

输出:

函数组件示例