一 、有狀態組件 (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>
)
}
兩都在性能方面比較,無狀態組件性能更高些。