组件,从概念上类似javaScript函数,它可以接受任何形式的入参(props),并返回用于描述页面展示内容的React元素,组件有两种形式:class组件和function组件
3.1class组件
class组件通常拥有状态和生命周期,继承于Component,实现render方法,用class创建一个Clock
import React,{Component} from "react"
export default class ClassComponent extends React.Component{
constructor(props){
super(props);
//使用state属性维护状态,在构造函数中初始化状态
this.state = {
date:new Date()
}
}
componentDidMount(){
//组件挂载之后启动定时器每秒更新状态
this.timerID = setInterval(()=>{
//使用setState方法更新状态
this.setState({
date:new Date()
})
},1000)
}
componentWillUnmount(){
//组件卸载前停止定时器
clearInterval(this.timerID)
}
componentDidUpdate(){
console.log("compoentDidUpdate");
}
render(){
return (
<div>
{this.state.date.toLocaleTimeString()}
</div>
)
}
}
3.2function组件
函数组件通常无状态,仅关注内容的展示,返回渲染结果即可(react16.8开始引入hooks,函数组件也能拥有状态)
用function组件创建一个Clock
import React,{useState,useEffect} from 'react'
export function FunctionComponent(props){
const [date,setDate] = useState(new Date());
useEffect(()=>{
const timer = setInterval(()=>{
setDate(new Date());
},1000)
return()=>clearInterval(timer);
},[])
return(
<div>
<h3>FunctionComponent</h3>
<p>{date.toLocaleTimeString()}</p>
</div>
)
}
可以把useEffect Hook看做componentDidMount、componentDidUpdate和componentwillUnmount这是三个组合
代码下载地址:https://gitee.com/JingYaBei/my-app.git