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

回答思路:类组件–>函数组件–>区别

类组件

通过ES6类的编写形式去编写组件,该类必须继承React.Component,通过this.props的方式去访问父组件传递过来的参数,且在类组件中必须使用render方法,在return中返回React对象,如下:

class Example extends React.Component{
	constructor(props){
		super(props)
	}
	render(){
		return <h1>Hello,{this.props.name}</h1>
	}
}

函数组件

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

function Example(props){
	return <h1>hello,{props.name}</h1>;
}

区别

1.编写形式不同
2.状态管理不同
3.生命周期不同
4.调用方式不同
5.获取渲染的值的方式不同

编写形式不同:

函数组件:

function Example(props){
	return <h1>hello,{props.name}</h1>;
}

类组件:

class Example extends React.Component{
	constructor(props){
		super(props)
	}
	render(){
		return <h1>Hello,{this.props.name}</h1>
	}
}

状态管理不同:

在hooks出来之前,函数组件是无状态组件,不能保管组件的状态,类组件使用setState来保管
函数组件:

const Example = ()=>{
	const [count,setCount] = React.useState(0);
	return (
		<div>
			<p>count:{count}</p>
			<button onClick={()=>setCount(count+1)}>click me</button>
		</div>
	)
}

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

生命周期不同:

函数组件不存在生命周期,生命周期钩子都来自于继承React.Component,所以只有类组件有生命周期,但是函数组件使用useEffect也能够完成替代生命周期的作用,例如:

const Example = () =>{
	useEffect(()=>{
		console.log("Hello");
	},[]);
	return <h1>hello</h1>;
}

这里的useEffect就相当于类组件中的componentDidMount生命周期,如果在useEffect中return一个函数,这个函数会在组件卸载的时候执行,相当于componentWillUnmount
例如:

const Example = () =>{
	useEffect(()=>{
		return ()=>{
			console.log("bye");	
		};
	},[]);
	return <h1>hello</h1>;
}

调用方式的不同:

函数组件:

const Example = () =>{
	return <h1>hello</h1>;
}
// React内部
const result = Example(props) //<h1>hello</h1>

类组件:

class Example extends React.Component{
	render(){
		return <h1>hello</h1>
	}
	
}
// React内部
const instance = new Example(props) //Example{}
const result = instance.render() //<h1>hello</h1>

获取渲染的值的方式不同

函数组件中获取值不需用this,如直接使用props.name,但是在类组件中必须要加上this,如this.props.name,两者看起来实现功能是一致的,但是在组件中,输出this.props.name,props在react中是不可改变的,但是this总是可以改变的,可以在render和生命周期函数中读取新版本,因此我们在组件请求运行时更新,this.props将会改变,而在函数组件中,不存在this,props并不会发生改变,因此函数组件在请求运行时更新,props不发生改变,props.name还是旧的name

小结:

两种组件都有各自的优缺点,函数组件语法更短、更简单,这使得它更容易开发、理解和测试,类组件使用大量的this,不易理解

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王 歪歪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值