react实现原理猜测

本文深入探讨了React框架解决的主要问题,包括组件复用、数据与视图同步,并通过实例剖析了React的工作原理。此外,还提供了一个简化版React的实现代码,帮助读者更好地理解其内部机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

react 解决的问题:

1前端组件的复用性问题:

        class Component{
    constructor(){}
setState(){}    
}    

2数据和视图的同步问题

class Sample extends Component{

    constructor(){

    super()

this.state={}

}

}

virtual-DOM 

jsx javascript 扩展

javascript对象描述

{

    tag:"div",

attrs:[],

    chaildrens:{

    tag:"div",

attrs:[],

}

}

3.react实现原理猜测

我们动手写一个有状态组件

class Button extends Component{

    constructor(props){

super(props)

this.state={clolor:red}

}

onClick(){

this.setState={

color:this.state.color

}

}

render(){

    return(

<button className="button"><button>

)

}

}

1.猜测return 方法的jsx的转译成对象,所以不能直接用 class  for等js的关键字

2.setState在Component 类里实现了render()功能,

3.Component 在constructor 实现了 construcor(props={}){
    this.props=props
}

4.setState的DOM更新使用了virtual-DOM

4 自己实现一个React

class Component{
  constructor(props={}){
  this.props=props
  }
  setState(state){
  this.state=state
  const oldEl=this.el
  let newEl=this.renderDOM()
  if(this.onStateChange){this.onStateChange(oldEl,newEl)}
  }
  renderDOM(){
  this.el=createDOMFromString(this.render())
  this.el.addEventListener("click",this.onClick.bind(this),false)
  return this.el
  }
  }
  const mount=(component,wrapper)=>{
  wrapper.appendChild(component.renderDOM())
  component.onStateChange=(oldEl,newEl)=>{
  wrapper.insertBefore(newEl,oldEl)
  wrapper.removeChild(oldEl)
  }
  }

完整代码见

https://github.com/bestGao/oursReact

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值