这是我参与8月更文挑战的第8天,活动详情查看:8月更文挑战
这是我写的第一篇有关react源码的文章,先说一下为啥要写这个系列
- 从刚开始用vue到自己开始用react已经过去了两年的时间,一直没有深入了解react的源码
- 看的解析很多,看得多了感觉自己懂了。但是从来没有写出来过,俗话说能让别人懂才是真的懂
版本
我阅读的react源码版本为17.0.2 这是我fork的代码仓库
前言
- 由于react代码庞大 这个系列可能会很长,每个部分都会分成几篇文章来写
- 由于代码太多 看文章的时候务必结合代码一起看 我就不贴上来了
- 我会把平时阅读代码的注释更新至github
先热个身
react-dom是react核心的库之一,react-dom 的 package 提供了可在应用顶层使用的 DOM(DOM-specific)方法,如果有需要,你可以把这些方法用于 React 模型以外的地方。不过一般情况下,大部分组件都不需要使用这个模块。
我们先看看react-dom抛出了哪一些方法
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
// Export all exports so that they're available in tests.
// We can't use export * from in Flow for some reason.
export {
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,
createPortal,
createRoot,
hydrateRoot,
findDOMNode,
flushSync,
hydrate,
render,
unmountComponentAtNode,
unstable_batchedUpdates,
unstable_createEventHandle,
unstable_flushControlled,
unstable_isNewReconciler,
unstable_renderSubtreeIntoContainer,
unstable_runWithPriority, // DO NOT USE: Temporarily exposed to migrate off of Scheduler.runWithPriority.
unstable_scheduleHydration,
version,
} from './src/client/ReactDOM';
可以看到react-dom抛出了从./src/client/ReactDOM引入的包括render createRoot等方法,我们先从最初接触react使用的render方法开始说起
render
render方法在提供的 container 里渲染一个 React 元素,并返回对该组件的引用(或者针对无状态组件返回 null)。
如果 React 元素之前已经在 container 里渲染过,这将会对其执行更新操作,并仅会在必要时改变 DOM 以映射最新的 React 元素。
如果提供了可选的回调函数,该回调将在组件被渲染或更新之后被执行。
ReactDOM.render(element, container[, callback])