小工具知识网

当前位置: 首页 > 行业知识 > 【 React 】对React中类组件和函数组件的理解?有什么区别?

行业知识

【 React 】对React中类组件和函数组件的理解?有什么区别?

2026-11-17 16:09:34 来源:互联网转载

���关文章:

()

1 React 中的类组件

2 React中的函数组件

()

1. 类组件

类组件,也就是通过使用ES6类的编写形式去编写组件,该类必须继承React.Component

如果想要访问父组件传递过来的参数,可以通过this.props方式去访问

在组件中必须实现render方法,再通return中返回React对象

// 类组件class Hello extends React.Component{    constructor(props){        super(props)    }    render(){        return 

hello,{this.props.name}

}}

2. 函数组件

函数组件,就是通过函数编写的形式去实现一个React组件,是React中定义组件最简单的方式

//函数组件function Hello(props){    return 

hello,{props.name}

}

函数组件第一个参数为props 用于接收父组件传递过来的参数

3. 区别

针对两种React组件,其区别主要分成以下几个方向:

  • 编写形式
  • 状态管理
  • 生命周期
  • 调用方式
  • 获取渲染的值

    3.1 编写形式

    两种最明显的区别在于编写的形式不同,同一种功能的实现可以分别对应类组件和函数组件的编写形式

    3.2 状态管理

    在hooks出来之前,函数组件就是无状态组件,不能保管组件的状态,不像类组件中调用的setState

    如果想要管理state状态,可以用useState,如下:

    const FunctionComponent=()=>{    const [count,setCount]=React.useState(0);    return (                    

    count:{count}

    ()={ setCount(count+1) }}>Click )}

    在使用hooks情况下,一般如果函数组件调用state,则需要创建一个类组件或者state提升到你的父组件中,然后通过props对象传递到子组件

    3.3 生命周期

    在函数组件中,并不存在生命周期 ,这是因为这些生命周期钩子都来自于继承的React.Component 所以,如果用到生命周期,就只能使用类组件

    但是函数组件使用useEffect也能够完成替代生命周期的作用,这里给出一个简单例子

    const FunctionComponent=()=>{    useEffect(()=>{        console.log('hello')    },[])    return 

    hello,world

    }

    上述例子对应类组件中的componentDidMount 生命周期

    如果useEffect回调函数中return 一个函数,则return 函数会在组件卸载的时候执行,整如componentWillUnmount

    const FunctionComponent=()=>{    React.useEffect(()=>{       return ()=>{        console.log('bye')       }    },[])    return 

    bye,world

    }

    3.4 调用方式

    如果是一个函数组件,调用则执行函数即可:

    function SayHi(){    return 

    hello ,rui

    }const result=SayHi(props) //

    hello ,rui

    如果是一个类组件,则需要将组件进行实例化,然后调用 实例对象render方法:

    //自己的代码class SayHi extends React.Component{    render(){        return 

    hello,rui

    }}//React 内部const instance=new SayHi(props) //SayHi{}const result=instance.render() //

    hello ,rui

    3.5 获取渲染的值

    函数组件代码对应如下

    function ProfilePage(props) {    const showInfo=()=>{        alert('Hi'+props.user)    }    const handleClick=()=>{        setTimeout(showInfo,5000)    }    return handleClick}Hi}

    类组件代码对应如下

    class ProfilePage extends React.Component{    showInfo(){        alert('Hi'+this.props.user)      }    handleClick(){        setTimeout(this.showInfo.bind(this),5000)    }    render(){        return this.handleClick.bind(this)}Hi    }}

    两者看起来实现的功能是一致的,但是在类组件中,输出this.props.user,Props在React中是不可变的所以他永远不会改变,但是this总是可变的,以便在render和生命周期函数中读取新版本

    因此,如果我们的组件在请求运行时更新。this.props将会改变。showInfo方法从最新的props中读取user

    函数组件,本身就不存在this,props 并不发生改变,因此同样点击,alert 的内容仍旧是之前的内容

    4.总结

    函数组件语法更短、更简单,这使得它更容易开发、测试和理解 。

    类组件会因为大量使用this让人困惑。

上一篇:揭秘光谷轻松下载秘籍,一站式指南助你轻松搞定!

下一篇:香港云服务器哪里的好?