有状态组件 和 无状态组件的区别


一 、有状态组件 (stateful components)

         平时用的大部分是 有状态组件

        写法:

        

import React,{Component} from 'react';

export default class Bottom extends Component{
constructor(props){
super(props);
this.sayHi = this.sayHi.bind(this)//记得绑定this,否则this指向可能会出错
}

sayHi(){
let {name} = this.props
console.log(`Hi ${name}`);
}
render(){
let {name} = this.props
let{sayHi} =this;
return(
<div>
<h1>{`Hello, ${name}`}</h1>
<button onClick ={sayHi}>Say Hi</button>
</div>
)
}

}

二、无状态组件 (stateless components)

       它是一种函数式组件,没有state, 接收Props,渲染DOM,而不关注其他逻辑

       写法:

        

import React,{Component} from 'react';
export default function Bottom(props){
let{name} = props
const sayHi = () => {
console.log(`Hi ${name}`);
}
return (
<div>
<h1>Hello, {name}</h1>
<button onClick ={sayHi}>Say Hi</button>
</div>
)
}


两都在性能方面比较,无状态组件性能更高些。

调用无状态组件方式, 方式 2 性能高:
1、<Bottom name="jason" />
2、Bottom({name: "jason"})
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM