react基础知识—3.组件

组件,从概念上类似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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值