• react 闲谈


    从事前端一段时间了,公司用的框架都是vue,但是不知为何对react却情有独钟,这是不是所谓的吃着碗里的看着锅里的 哈哈哈
    从头好好总结下react吧 小白一个 大神勿喷

    瞎说一

    1. react是由两部分组成,react包和react-dom,语法呢都是ES6,那ReactDOM中最常用的方法呢就是render
    2. 那说到react 不得不说一个JSX元素, 此乃何物,这么说 它是JavaScript 与 xml 爱情的结晶 哈哈哈 那么html也是xml的一种 所以 就是javascript + html;JSX 中的html部分和原生的html基本一样,也不完全一样,JSX是一个语法糖 最后通过babel进行转义
      ReactDOM.render的写法
    React.createElement(
      "h1",
      { className: "red" },
      "简直走别拐弯",
      React.createElement(
          "span",
          { id: "handsome" },
          "帅哥"
      )
    )
    
    • 最终会转化成一个对象"虚拟dom" {type:'h1',props:{className:"red",children:[简直走别拐弯,{type:'span',props:{id:'handsome',children:'帅哥'}]}}
    • 1.先将jsx转化成react元素
    • 2.将react元素变成一个对象
    • 3.通过render方法渲染出一个对象

    瞎说二

    1.createElement简单实现

    function createElement (type,props,...children)  {
            if(childern.length === 1){
                return {type,props:{...props,children:children}}
    
        }
    
    }
    // {type:'h1',props:{className:"red",children:[简直走别拐弯,{type:'span',props:{id:'handsome',children:'帅哥'}]}}
    
    
    let myRender = (obj,container) =>{
        let {type,props} = obj;
        let ele = document.createElement(type); // 创建第一层
        for(let key in props){
            if(key === 'children'){
                // children有可能是数组 也可能是一个
                if(typeof props[key] === 'object'){ // 数组 ['姜,',{type:'',props:{}}]
                    props[key].forEach(item=>{
                        if(typeof item === 'object'){ // 如果子元素是对象那就继续调用render
                            myRender(item,ele);
                        }else{
                            ele.appendChild(document.createTextNode(item));
                        }
                    })
                }else{ // 一个的化直接插入到h1中
                    ele.appendChild(document.createTextNode(props[key]));
                }
            }else if(key === 'className'){
                ele.setAttribute('class',props[key]);
            }else{
                ele.setAttribute(key,props[key]);
            }
        }
        container.appendChild(ele);// 将元素插入到页面中
    }; // 将我们自己创建出来的“元素”对象 插入到root中
    myRender(createElement("h1",{className: "red"},"简直走别拐弯,", createElement("span",{id: "handsome"},"帅哥")),document.getElementById('root'));
    
    
    
  • 相关阅读:
    【BZOJ4520】[Cqoi2016]K远点对 kd-tree+堆
    【BZOJ2843】极地旅行社 离线+树链剖分+树状数组
    【BZOJ3251】树上三角形 暴力
    SQL学习笔记三(补充-3)之MySQL完整性约束
    SQL学习笔记三(补充-2)之MySQL数据类型
    SQL学习笔记三(补充-1)之MySQL存储引擎
    SQL学习笔记二之MySQL的数据库操作
    SQL学习笔记一之初识数据库
    深入理解Python中的元类(metaclass)
    Web安全之BurpSuite抓取HTTPS请求
  • 原文地址:https://www.cnblogs.com/wzy0526/p/9935678.html
Copyright © 2020-2023  润新知