基于类的组件与功能组件有什么区别(Reactjs) [英] Class based component vs Functional components what is the difference ( Reactjs )

查看:351
本文介绍了基于类的组件与功能组件有什么区别(Reactjs)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React 的新手,我想清楚地知道要使用哪一个,当涉及到组件我会看到有两种类型。

I am new to React and I want to have a clear idea of which one to use, when it comes to components I get to see there are two types.

功能组件:

import React from 'react'

const userInput = (props) => {
    return(
        <div>
            <input type='text' onChange={props.nameChanged} value={props.username}></input>
        </div>
    )
};

export default userInput;

基于类别的组件:

import React, { Component } from 'react';
import './App.css';
import UserOutput from './UserOutput/UserOutput';
import UserInput from './UserInput/UserInput';

class App extends Component {

  render() {
    return (
      <div className="App">
        <h3>Assignment Output :</h3>
        <ul>
          <li>
            <UserOutput 
            username={this.state.Usernames[0].username}>
            Welcome to React!
            </UserOutput>
            <UserInput 
            nameChanged={this.nameChangedHandler}>
            </UserInput>
          </li>
                      </ul>
      </div>
    );
  }
}

export default App;

我读到我们应该总是尝试使用功能组件因为它有助于某些事情并且还听说我们应该尽可能避免使用基于类的组件

I get to read that we should always try to use a Functional component because it helps in some things and also heard that we should avoid using a Class based component as much as possible.

我很困惑哪个是对的,哪个不对。

I am confused which is right and which is not.

为什么要尝试使用功能组件可能的,有什么好处?

Why should try to use Functional component where ever its possible, what are the benefits ?

我们什么时候应该选择功能组件,什么时候不用,不清楚。

When should we go for a Functional component and when not, is not clear.

推荐答案

班级组件


  • 班级 - 基于Components的组件使用ES6类语法。它可以使用生命周期方法。

  • Class-based Components uses ES6 class syntax. It can make use of the lifecycle methods.

正如您在示例中所看到的,您已经从React.Component扩展了上面的类组件。

As you can see in the example that u have given above Class components extend from React.Component.

在这里,你必须使用这个关键字来访问你在类组件中声明的道具和函数。

In here you have to use this keyword to access the props and functions that you declare inside the class components.

功能组件


  • 功能组件与基于类的函数相比更简单。

  • Functional Components are simpler comparing to class-based functions.

功能组件主要关注应用程序的UI,而不是行为。

Functional Components mainly focuses on the UI of the application, not on the behavior.

更准确地说,这些基本上是
类组件中的渲染函数。

To be more precise these are basically render function in the class component.

功能组件可以没有状态,他们不能使用生命周期方法

Functional Components can't have state and they can't make use of lifecycle methods.

这篇关于基于类的组件与功能组件有什么区别(Reactjs)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆