手動(dòng)實(shí)現(xiàn)react.js

index.js

引入了自定義的React和ReactDOM,定義了jsx模板荆虱,里面有class組件(繼承自定義的React.Component),原生標(biāo)簽和function組件朽们,使用了自定義ReactDOM.render方法渲染模板

kReact/index.js

引入了自定義Component,實(shí)現(xiàn)createElement方法怀读,根據(jù)傳入的type判斷是什么節(jié)點(diǎn),并保存children到props上

react-dom.js

把傳入的虛擬節(jié)點(diǎn)轉(zhuǎn)化為真實(shí)節(jié)點(diǎn) append到容器上

virtual-dom.js

根據(jù)傳入的虛擬節(jié)點(diǎn)骑脱,取出他們各自的類型 用不同的方法生成真實(shí)dom

Component.js

定義了Component class保存?zhèn)魅氲膒rops 增加屬性isReactComponent以區(qū)分是class組件還是function組件 實(shí)現(xiàn)了setState菜枷,setState內(nèi)部執(zhí)行forceUpdate方法

diff.js

把傳入的新虛擬節(jié)點(diǎn)轉(zhuǎn)化為真實(shí)節(jié)點(diǎn) 替換舊的節(jié)點(diǎn)

index.js

// import React, { Component } from "react";
// import ReactDOM from "react-dom";

// import React from "./kkreact/";
// import ReactDOM from "./kkreact/ReactDOM";

import React from "./kReact";
import ReactDOM from "./kReact/react-dom";

import "./index.css";

class ClassCpm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0,
    };
  }
  handle = () => {
    this.setState({
      counter: this.state.counter + 1,
    });
    console.log("handle", this.state.counter);
  };
  render() {
    return (
      <div className="border">
        {this.props.name}
        <button onClick={this.handle}>{this.state.counter}</button>
        {[0, 1, 2].map(item => {
          return <FuncCmp key={item} name={"function組件" + item} />;
        })}
      </div>
    );
  }
}

function FuncCmp(props) {
  return <div className="border">{props.name}</div>;
}

let jsx = (
  <div className="box border">
    <p className="border">這是React</p>
    <FuncCmp name="function組件" />
    <ClassCpm name="class組件" />
  </div>
);

ReactDOM.render(jsx, document.getElementById("root"));

index.css

body {
  margin: 20px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.border {
  margin: 10px;
  padding: 10px;
  border: solid 1px red;
}

src/kReact/index.js

import Component from "./Component";

function createElement(type, props, ...children) {
  // console.log("arg", arguments);
  props.children = children;
  let vtype; //如果是文本節(jié)點(diǎn), 就是undefined
  if (typeof type === "string") {
    //原生標(biāo)簽
    vtype = 1;
  } else if (typeof type === "function") {
    //class: 2, function: 3
    vtype = type.isReactComponent ? 2 : 3;
  }
  return {
    vtype,
    type,
    props,
  };
}

export default {
  createElement,
  Component,
};

src/kReact/react-dom.js

import { initVnode } from "./virtual-dom";

function render(vnode, container) {
  //vnode->node
  const node = initVnode(vnode, container);
  container.appendChild(node);
}

export default {
  render,
};

src/kReact/Component.js

import { diff } from "./diff";

class Component {
  static isReactComponent = {};
  constructor(props) {
    this.props = props;
    this.$cache = {};
    this.state = {};
  }
  setState = (nextState, callback) => {
    ///這是個(gè)假的setState
    this.state = {
      ...this.state,
      ...nextState,
    };
    this.forceUpdate();
  };
  forceUpdate = () => {
    console.log("setState");
    let newVnode = this.render();
    const newNode = diff(this.$cache, newVnode);
    //vnode newVnode ->node
    this.$cache = {
      ...this.$cache,
      vnode: newVnode,
      node: newNode,
    };
  };
}

export default Component;

src/kReact/virtual-dom.js

export function initVnode(vnode, container) {
  //vnode->node
  const { vtype } = vnode;
  let node;
  if (!vtype) {
    node = initTxtNode(vnode, container);
  }
  if (vtype === 1) {
    //原生標(biāo)簽
    node = initHtmlNode(vnode, container);
  }
  if (vtype === 2) {
    //class組件
    node = initClassNode(vnode, container);
  }
  if (vtype === 3) {
    //function組件
    node = initFunctionNode(vnode, container);
  }
  return node;
}

function initTxtNode(vnode, container) {
  const node = document.createTextNode(vnode);
  return node;
}

//原生vnode->node
function initHtmlNode(vnode, container) {
  const { type, props } = vnode;
  const node = document.createElement(type);
  const { children, ...rest } = props;
  children.map(item => {
    if (Array.isArray(item)) {
      item.map(c => {
        node.appendChild(initVnode(c, node));
      });
    } else {
      node.appendChild(initVnode(item, node));
    }
  });
  for (let key in rest) {
    if (key === "className") {
      node.setAttribute("class", rest[key]);
    } else if (key.slice(0, 2) === "on") {
      node.addEventListener("click", rest[key]);
    }
  }
  return node;
}

function initFunctionNode(vnode, container) {
  const { type, props } = vnode;
  const node = type(props); //vnode
  return initVnode(node, container);
}

function initClassNode(vnode, container) {
  const { type, props } = vnode;
  const componet = new type(props);
  const vvnode = componet.render(); //vnode
  const node = initVnode(vvnode, container);
  componet.$cache = {
    vnode: vvnode,
    node,
    parentNode: container,
  };
  return node;
}

src/kReact/diff.js

import { initVnode } from "./virtual-dom";

//這不是diff
export function diff(cache, newVnode) {
  console.log("new", newVnode);
  const { vnode, node, parentNode } = cache;
  const newNode = initVnode(newVnode, parentNode);
  console.log("con", parentNode);
  parentNode.replaceChild(newNode, node);
  return newNode;
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末惜姐,一起剝皮案震驚了整個(gè)濱河市犁跪,隨后出現(xiàn)的幾起案子椿息,更是在濱河造成了極大的恐慌歹袁,老刑警劉巖坷衍,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異条舔,居然都是意外死亡枫耳,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進(jìn)店門孟抗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來迁杨,“玉大人,你說我怎么就攤上這事凄硼∏π” “怎么了?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵摊沉,是天一觀的道長狐史。 經(jīng)常有香客問我,道長说墨,這世上最難降的妖魔是什么骏全? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮尼斧,結(jié)果婚禮上姜贡,老公的妹妹穿的比我還像新娘。我一直安慰自己棺棵,他們只是感情好楼咳,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著烛恤,像睡著了一般爬橡。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上棒动,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天糙申,我揣著相機(jī)與錄音,去河邊找鬼船惨。 笑死柜裸,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的粱锐。 我是一名探鬼主播疙挺,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼怜浅!你這毒婦竟也來了铐然?” 一聲冷哼從身側(cè)響起蔬崩,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎搀暑,沒想到半個(gè)月后沥阳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡自点,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年桐罕,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片桂敛。...
    茶點(diǎn)故事閱讀 40,001評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡功炮,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出术唬,到底是詐尸還是另有隱情薪伏,我是刑警寧澤,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布粗仓,位于F島的核電站嫁怀,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏潦牛。R本人自食惡果不足惜眶掌,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望巴碗。 院中可真熱鬧朴爬,春花似錦、人聲如沸橡淆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽逸爵。三九已至具滴,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間师倔,已是汗流浹背构韵。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留趋艘,地道東北人疲恢。 一個(gè)月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像瓷胧,于是被迫代替她去往敵國和親显拳。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,955評論 2 355