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

一 、有状态组件 (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"})
 
posted @ 2019-07-01 15:25  goodman8  阅读(6866)  评论(2编辑  收藏  举报