React16源码: memo, Fragment, StrictMode, cloneElement, createFactory源码实现

本文主要是介绍React16源码: memo, Fragment, StrictMode, cloneElement, createFactory源码实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

memo


1 ) 概述

  • memo 在react 16.6 推出的一个API
  • 它的用意是让 function component,有一个类似 PureComponent 的一个功能
    • PureComponent 提供了 class component 组件类型
    • 在props没有变化的情况下,它可以不重新渲染
  • 目的是给 function component 做一个 PureComponent 的对标
  • 这个用法很简单,就不进行举例了

2 ) 源码解析

// memo.js/*** 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.*/import {REACT_MEMO_TYPE} from 'shared/ReactSymbols';import isValidElementType from 'shared/isValidElementType';
import warningWithoutStack from 'shared/warningWithoutStack';export default function memo<Props>(type: React$ElementType,compare?: (oldProps: Props, newProps: Props) => boolean,
) {if (__DEV__) {if (!isValidElementType(type)) {warningWithoutStack(false,'memo: The first argument must be a component. Instead ' +'received: %s',type === null ? 'null' : typeof type,);}}return {$$typeof: REACT_MEMO_TYPE,type,compare: compare === undefined ? null : compare,};
}
  • 可以看到 memo 是一个方法
  • 第一个参数 type 可以是 function component
  • 第二个参数 compare
    • 是一个 old props 和 new props 的对比方法
    • 返回值是 boolean,类似于 SCU
  • 最终的返回值是一个对象
    • $$typeofREACT_MEMO_TYPE
    • type,就是我们传入的 function component
    • compare 是我们传入的第3个参数
    • 所以它就跟之前的 forwardRef, context 差不多一类的东西
    • 最终它实现的逻辑肯定还是要到 react-dom 那边来实现的

Fragment


1 ) 概述

  • Fragment 实际上是一个 Symbol
  • 在我们项目代码中的 <></> 实际上等价于 <React.Fragment><React.Fragment />
  • 这是React 渲染函数 render 中返回的单个节点的约束和无用div节点的平衡处理

2 )源码

// React.jsFragment: REACT_FRAGMENT_TYPE,
  • 从概述中得知,本身这个节点没有任何的意义
  • 它也不会生成多余的节点,只是告诉 react 里面是有多个兄弟节点
  • 本身就是一个 Symbol,没有特殊的含义
  • 它的作用就是用于包裹节点

StrictMode


1 ) 概述

  • StrictMode 本质是一个组件
  • 它的作用是在渲染内部组件时,发现不合适的代码并给出提醒

2 )源码

  // React.jsStrictMode: REACT_STRICT_MODE_TYPE,
  • 实际上它也是一个 Symbol
  • 它就跟 ConcurrentMode 是差不多的意思
  • 它这个节点下面的所有子树都要按照某一种模式进行渲染
  • 对于其规则下面的所有子树的节点,会给我们提供一些过时的API的提醒
    • 比如说在某个节点下面,使用了 componentWilMount 这种将要过期的生命周期方法的时候
    • 它就会做出提醒,说你这个方法是不好的,你不应该这么去做
    • 它使用方式也是像 react component,所以影响的范围仅仅是它的子树
  • 类似于 ConcurrentMode, 在它的节点下面才会是有一个异步渲染情况

cloneElement


1 ) 概述

  • 对原 ReactElement 进行克隆处理
  • 返回一个新的ReactElement

2 )源码分析

直接定位在 ReactElement.js

  // ReactElement.jsexport function cloneElement(element, config, children) {invariant(!(element === null || element === undefined),'React.cloneElement(...): The argument must be a React element, but you passed %s.',element,);let propName;// Original props are copiedconst props = Object.assign({}, element.props);// Reserved names are extractedlet key = element.key;let ref = element.ref;// Self is preserved since the owner is preserved.const self = element._self;// Source is preserved since cloneElement is unlikely to be targeted by a// transpiler, and the original source is probably a better indicator of the// true owner.const source = element._source;// Owner will be preserved, unless ref is overriddenlet owner = element._owner;if (config != null) {if (hasValidRef(config)) {// Silently steal the ref from the parent.ref = config.ref;owner = ReactCurrentOwner.current;}if (hasValidKey(config)) {key = '' + config.key;}// Remaining properties override existing propslet defaultProps;if (element.type && element.type.defaultProps) {defaultProps = element.type.defaultProps;}for (propName in config) {if (hasOwnProperty.call(config, propName) &&!RESERVED_PROPS.hasOwnProperty(propName)) {if (config[propName] === undefined && defaultProps !== undefined) {// Resolve default propsprops[propName] = defaultProps[propName];} else {props[propName] = config[propName];}}}}// Children can be more than one argument, and those are transferred onto// the newly allocated props object.const childrenLength = arguments.length - 2;if (childrenLength === 1) {props.children = children;} else if (childrenLength > 1) {const childArray = Array(childrenLength);for (let i = 0; i < childrenLength; i++) {childArray[i] = arguments[i + 2];}props.children = childArray;}return ReactElement(element.type, key, ref, self, source, owner, props);}
  • 首先,它把props首先复制过来,const props = Object.assign({}, element.props);
  • 然后呢把key和 ref 也复制过来 然后再进行一些处理
  • 其实就是创建一个新的 React Element
  • 其实整体的过程是跟 createElement 是差不多的
  • 只不过它是传入了一个 element,然后他进行一个克隆这么一个过程

createFactory


1 ) 概述

  • 返回一个某种类型的 ReactElement 工厂函数
  • 可以利用返回的函数来创建一个 ReactElement

2 )源码分析

export function createFactory(type) {const factory = createElement.bind(null, type);// Expose the type on the factory and the prototype so that it can be// easily accessed on elements. E.g. `<Foo />.type === Foo`.// This should not be named `constructor` since this may not be the function// that created the element, and it may not even be a constructor.// Legacy hook: remove itfactory.type = type;return factory;
}
  • 这个源码比较简洁
  • createFactory 对于写 jsx 的场景几乎是不可能用到的
  • 因为 createFactory 是对 createElement 的一个封装
    • createFactorycreateElement 绑定了一个type
    • 比如说我们要去创建一个p标签的节点
      • 如果使用 JS API去创建,比如使用 createElement
      • 每次都要先传入 p,然后再传入 config,再传入它的children
  • 其实,我们可以先创建一个p标签的 factory
    • 通过这个factory返回的方法,我们只需要传入config和children,就可以创建一个p标签
    • 而不需要重复的去传p这个字符串来表示我们要创建的是p标签的节点

这篇关于React16源码: memo, Fragment, StrictMode, cloneElement, createFactory源码实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/564767

相关文章

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

Linux下删除乱码文件和目录的实现方式

《Linux下删除乱码文件和目录的实现方式》:本文主要介绍Linux下删除乱码文件和目录的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux下删除乱码文件和目录方法1方法2总结Linux下删除乱码文件和目录方法1使用ls -i命令找到文件或目录

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Linux在线解压jar包的实现方式

《Linux在线解压jar包的实现方式》:本文主要介绍Linux在线解压jar包的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux在线解压jar包解压 jar包的步骤总结Linux在线解压jar包在 Centos 中解压 jar 包可以使用 u

c++ 类成员变量默认初始值的实现

《c++类成员变量默认初始值的实现》本文主要介绍了c++类成员变量默认初始值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录C++类成员变量初始化c++类的变量的初始化在C++中,如果使用类成员变量时未给定其初始值,那么它将被