-
-
Notifications
You must be signed in to change notification settings - Fork 233
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
1.JSX 和 Virtual DOM #24
Comments
讲的挺好的,感谢! |
@limengke123 拿 React 来说,JSX 经过 babel 编译为 React.createElement() 的形式,所以要引人 React,从而调用其 createElement 方法生成 Virtual DOM。 |
你写的文章很好,通俗易懂,谢谢作者的分享 |
@Y-wson 可以动手实现一遍,收获会很大。 |
@MuYunyun |
@Y-wson 可以在 release 找到与文章对应的相应代码。 |
@MuYunyun 你的代码可以复制么?当然会加上自己的见解 |
@Y-wson 如果是学习用的话,在文章后面注明引用,我蛮欢迎的。另外如果对代码部分有什么好的见解可以交流 |
好的,我也是才学习源码,觉得你的文章通俗易懂,多向你学习 |
if (typeof(vdom) === 'string') {
container.innerText = vdom
return
} 这里要改成用 整体还有不少细节的小问题,建议作者可以构造一些单元测试,这些问题都能测出来。 |
@MuYunyun 你的测试文件 VDOM 结构太简单了,没有覆盖多个 <div>
child - 1
<span>child - 2</span>
child - only show this
</div> 如果不用 |
@PPQ1991 我明白你的意思了,在后面的章节中是有解决这个问题的,比如第二章中采用如下的方式来优化: if (_.isString(vdom) || _.isNumber(vdom)) {
container.innerText = container.innerText + vdom
return
} 以及再后面章节更为优化的代码,这是一个循序渐进的过程。 if (_.isString(vdom) || _.isNumber(vdom)) {
const textNode = document.createTextNode(vdom)
return textNode
} 因为这是一个从 0 到 1 实现 react 的过程,很多细节不能构思得一步到位。后面的章节中在增加新特性的时候也会补充前面遗留的坑。感谢持续跟进与交流。 |
你这里面有个小错误,setAttribute里面匹配事件的正则不应该加引号 |
@Y-wson 已更正 |
该系列文章在实现 cpreact 的同时理顺 React 框架的核心内容
环境准备
首先安装以下 babel 模块,其具体作用会在后文 JSX 和 虚拟 DOM 中提及
同时
.babelrc
配置如下:配置好 babel 后,接着提供两套打包工具的配置方案,读者可以自行选择。
方案 1:使用 webpack
webpack 拥有一个活跃的社区,提供了更为丰富的打包能力。
首先安装以下模块:
在根目录的
webpack.config.js
配置如下:然后在
package.json
里加上如下配置:具体可以参照 0.4.3 版本
方案 2:使用 parcel
parcel 是一款上手极快的打包工具,使用其可以快速地进入项目开发的状态。在
package.json
加上如下配置,具体可以参照 0.1 版本JSX 和 虚拟 DOM
JSX 是一种语法糖,经过 babel 转换结果如下,可以发现实际上转化成
React.createElement()
的形式:打印 element, 结果如下:
因此,我们得出结论:JSX 语法糖经过 Babel 编译后转换成一种对象,该对象即所谓的
虚拟 DOM
,使用虚拟 DOM 能让页面进行更为高效的渲染。我们按照这种思路进行函数的构造:
虚拟 DOM 转化为真实 DOM
上个小节介绍了 JSX 转化为虚拟 DOM 的过程,这个小节接着来实现将虚拟 DOM 转化为真实 DOM (页面上渲染的是真实 DOM)。
我们知道在 React 中,将虚拟 DOM 转化为真实 DOM 是使用
ReactDOM.render
实现的,使用如下:接着来实现
ReactDOM.render
的逻辑:至此,我们成功将虚拟 DOM 复原为真实 DOM,展示如下:
另外配合热更新,在热更新的时候清空之前的 dom 元素,改动如下:
总结
JSX
经过 babel 编译为 React.createElement() 的形式,其返回结果就是Virtual DOM
,最后通过 ReactDOM.render() 将 Virtual DOM 转化为真实的 DOM 展现在界面上。流程图如下:思考题
如下是一个 react/preact 的常用组件的写法,那么为什么要 import 一个 React 或者 h 呢?
项目说明
该系列文章会尽可能的分析项目细节,具体的还是以项目实际代码为准。
鸣谢
Especially thank simple-react for the guidance function of this library. At the meantime,respect for preact and react
The text was updated successfully, but these errors were encountered: