×

React中功能组件和类组件之间的区别

作者:Terry2021.04.02来源:Web前端之家浏览:5791评论:2
关键词:react

制作一个计数器应用程序,当用户使用“功能”和“类”组件单击“添加”按钮时,该应用程序将增加计数数量。

功能组件:功能组件是在React中工作时会遇到的一些更常见的组件。这些只是JavaScript函数。我们可以通过编写JavaScript函数来创建React的功能组件。

语法:

const Car=()=> {
  return <h2>Hi, I am also a Car!</h2>;
}

例子:

Javascript:

import React ,{useState} from "react";
 
const FunctionalComponent=()=>{
    const[count , setCount]=useState(0);
 
    const increase=()=>{
        setCount(count+1);
    }
 
    return (
        <div style={{margin:'50px'}}>
            <h1>Welcome to Geeks for Geeks </h1>
            <h3>Counter App using Functional Componenet : </h3>
            <h2>{count}</h2>
            <button onClick={increase}>Add</button>
        </div>
    )
}
 
export default FunctionalComponent;

输出结果:

functionalc.png

类组件:这是大多数用ReactJS构建的现代Web应用程序的基础。这些组件是简单的类(由向应用程序添加功能的多个功能组成)。

语法:

class Car extends React.Component {
  render() {
    return <h2>Hi, I am a Car!</h2>;
  }
}

例子:

Javascript:

import React from "react";
 
class ClassComponent extends React.Component{
    constructor(){
        super();
        this.state={
            count :0
        };
        this.increase=this.increase.bind(this);
    }
     
   increase(){
       this.setState({count : this.state.count +1});
   }
 
    render(){
        return (
            <div style={{margin:'50px'}}>
               <h1>Welcome to Geeks for Geeks </h1>
               <h3>Counter App using Class Componenet : </h3>
               <h2> {this.state.count}</h2> 
               <button onClick={this.increase}> Add</button>
 
            </div>
        )
    }
}
 
export default ClassComponent;

输出结果:

Cfinal.png

挂钩是React 16.8中的新增功能。它们使您无需编写类即可使用状态和其他React功能。

在上面的示例中,对于功能组件,我们使用钩子(useState)来管理状态。如果编写功能组件并意识到需要向其添加一些状态,则以前必须将其转换为类组件。现在,您可以在现有功能组件内部使用一个Hook来管理状态,而无需将其转换为Class组件。可以使用Function组件中的Hooks代替Class,因为这是一种管理状态的简便得多的方法。挂钩只能在功能组件中使用,不能在类组件中使用。

功能组件与类组件:


功能组件类组件
功能组件只是一个普通的JavaScript函数,它接受props作为参数并返回React元素。一个类组件需要您从React扩展。组件并创建一个渲染函数,该函数返回一个React元素。
功能组件中没有使用渲染方法。它必须具有返回HTML的render()方法
也称为无状态组件,因为它们仅接受数据并以某种形式显示,它们主要负责呈现UI。也称为有状态组件,因为它们实现逻辑和状态。
React生命周期方法(例如componentDidMount)不能在功能组件中使用。可以在类组件内部使用React生命周期方法(例如componentDidMount)。


您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/reactjs20210402.html

网友评论文明上网理性发言 已有2人参与

发表评论:

评论列表