React16源码: JSX2JS及React.createElement源码实现

React源码分析1-jsx转换及React.createElement 本章讲述了 jsx 在 react17 之前和之后的不同的转换,实际上 react17 之后 babel 的对 jsx 的转换就是比之前多了一步的动作:另外讲述了和的内部实现是怎样的。通过 babel及,将 jsx 转换为了浏览器能够识别的原生 js 语法,为 react 后续对状态改变、事件响应以及页面更新等奠定了基础。后面的章节中,将探究 react 是如何一步步将状态等信息渲染为真实页面的。 阅读详情

JSX 到 Javascript 的转换

  • React中的 JSX 类似于 Vue中的template模板文件,Vue是基于编译时将template模板转换成render函数
  • 在React中,JSX是类似于html和javascript混编的语法,而javascript是真的javascript, html并非真的html
  • 它的可阅读性可维护性都是要高很多的

1 )JSX2JS 原理

  • JSX 通过 babel 进行转换之后,生成了纯JS
    • JSX相对于JS来讲,它唯一的一个区别,就是它可以写类似于HTML的一个标签
    • 比如说我们通过写div 然后在 div 这种方式去声明HML的标签
    • 然后它会给我们返回在React当中需要使用的对象
  • 这就是JSX到JS的一个转化过程

2 ) 工具演示

  • 这个工具是 babel playground
  • 要做一些代码转化的一个测试,可以直接到这个playground上面来
    • 它会实时在为我们展现出我们写的代码转化出来的是什么样的样子
    • 下面的示例是使用较低版本的 babel 来配合 React 16.6 版本

示例1

jsx

<div></div>

js

React.createElement("div", null);

示例2

jsx

<div class="test"></div>

js

React.createElement("div", {
  class: "test"
});

示例3

jsx

<div id="div" key="key" class="test">
  <span>1</span>
  <span>1</span>
</div>

js

React.createElement("div", {
  id: "div",
  key: "key",
  class: "test"
}, React.createElement("span", null, "1"), React.createElement("span", null, "1"));

示例4

jsx

function Comp() {
  return <a>123</a>
}

<Comp id="div" key="key">
  <span>1</span>
  <span>1</span>
  <div id="box">
  	<span class='inner'>2</span>
  </div>
</Comp>

js

function Comp() {
  return React.createElement("a", null, "123");
}

React.createElement(Comp, {
  id: "div",
  key: "key"
}, 
	React.createElement("span", null, "1"),
	React.createElement("span", null, "1"),
	React.createElement("div", {
	  id: "box"
	}, 
		React.createElement("span", {
		  class: "inner"
		}, "2")
	)
);

3 )说明

  • 从上面我们可以看出来我们的一个类似html的标签,或者是组件的一个标签
  • 通过这种尖括号的方式来写的,它最终都会转换成 React.createElement
  • 我们写的这些标签或者一些props,或者它的 children 都会作为一个参数
    • props 是一个 key-value 形式的一个对象
    • 它可以支持多层,无限层的嵌套,也就是一个树形结构
  • 如果是一个函数式的组件作为参数
    • 这里要分两种情况
      • 1 ) 组件是大写的,这样会直接转换成变量(对象)
      • 2 ) 组件是小写的,这样会直接变成字符串类型的标记(组件将失效)
    • 注意
      • 如果变成字符串,那么在React中,它是会认为这是一个原生的dom节点的
      • 如果不存在这么一个dom节点,那么后续在运行的时候,可能就报错了
      • 所以自定义的组件必须使用大写的开头,这是一个规范
  • 综上,我们现在问题的重点就在 createElement 之上了

React.createElement 源码解析

  • 在上一步的 JSX2JS中,我们的标签,标签里的属性,标签的内容,都会变成各种类型的参数
  • 传到我们调用的 createElement 这个方法里面,这个方法内部如何实现的
  • 在 createElement 函数的内部,返回了一个 React Element, 我们来看看它具体的作用
  • 看源码肯定要从它的入口文件开始看,因为入口文件会给我们很多的信息告诉我们
  • 常用的使用这个包的时候的这些API它都来自于哪里,以及它是如何 export 出来的

1 )React 入口文件 packages/react/src/React.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 ReactVersion from 'shared/ReactVersion';
import {
  REACT_CONCURRENT_MODE_TYPE,
  REACT_FRAGMENT_TYPE,
  REACT_PROFILER_TYPE,
  REACT_STRICT_MODE_TYPE,
  REACT_SUSPENSE_TYPE,
} from 'shared/ReactSymbols';

import {Component, PureComponent} from './ReactBaseClasses';
import {createRef} from './ReactCreateRef';
import {forEach, map, count, toArray, only} from './ReactChildren';
import {
  createElement,
  createFactory,
  cloneElement,
  isValidElement,
} from './ReactElement';
import {createContext} from './ReactContext';
import {lazy} from './ReactLazy';
import forwardRef from './forwardRef';
import memo from './memo';
import {
  createElementWithValidation,
  createFactoryWithValidation,
  cloneElementWithValidation,
} from './ReactElementValidator';
import ReactSharedInternals from './ReactSharedInternals';
import {enableStableConcurrentModeAPIs} from 'shared/ReactFeatureFlags';

const React = {
  Children: {
    map,
    forEach,
    count,
    toArray,
    only,
  },

  createRef,
  Component,
  PureComponent,

  createContext,
  forwardRef,
  lazy,
  memo,

  Fragment: REACT_FRAGMENT_TYPE,
  StrictMode: REACT_STRICT_MODE_TYPE,
  Suspense: REACT_SUSPENSE_TYPE,

  createElement: __DEV__ ? createElementWithValidation : createElement,
  cloneElement: __DEV__ ? cloneElementWithValidation : cloneElement,
  createFactory: __DEV__ ? createFactoryWithValidation : createFactory,
  isValidElement: isValidElement,

  version: ReactVersion,

  __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactSharedInternals,
};

if (enableStableConcurrentModeAPIs) {
  React.ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
  React.Profiler = REACT_PROFILER_TYPE;
} else {
  React.unstable_ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
  React.unstable_Profiler = REACT_PROFILER_TYPE;
}

export default React;
  • 上面全是 import 其他一些东西,import 进来之后, 它声明了 React 对象
  • 这个对象就是我们在外部去用 React 的时候,给我们提供的API
  • 然后最终它 export default React 把这个对象给它 export 出来
  • 这样的话我们就可以在外部使用
  • 我们回到 createElement 上面来,从上面可知,跟Element相关的一些代码
  • 都放在了 ./ReactElement 这个文件下面

2 )定位到 ReactElement.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 invariant from 'shared/invariant';
import warningWithoutStack from 'shared/warningWithoutStack';
import {REACT_ELEMENT_TYPE} from 'shared/ReactSymbols';

import ReactCurrentOwner from './ReactCurrentOwner';

const hasOwnProperty = Object.prototype.hasOwnProperty;

const RESERVED_PROPS = {
  key: true,
  ref: true,
  __self: true,
  __source: true,
};

let specialPropKeyWarningShown, specialPropRefWarningShown;

function hasValidRef(config) {
  if (__DEV__) {
    if (hasOwnProperty.call(config, 'ref')) {
      const getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
      if (getter && getter.isReactWarning) {
        return false;
      }
    }
  }
  return config.ref !== undefined;
}

function hasValidKey(config) {
  if (__DEV__) {
    if (hasOwnProperty.call(config, 'key')) {
      const getter = Object.getOwnPropertyDescriptor(config, 'key').get;
      if (getter && getter.isReactWarning) {
        return false;
      }
    }
  }
  return config.key !== undefined;
}

function defineKeyPropWarningGetter(props, displayName) {
  const warnAboutAccessingKey = function() {
    if (!specialPropKeyWarningShown) {
      specialPropKeyWarningShown = true;
      warningWithoutStack(
        false,
        '%s: `key` is not a prop. Trying to access it will result ' +
          'in `undefined` being returned. If you need to access the same ' +
          'value within the child component, you should pass it as a different ' +
          'prop. (https://fb.me/react-special-props)',
        displayName,
      );
    }
  };
  warnAboutAccessingKey.isReactWarning = true;
  Object.defineProperty(props, 'key', {
    get: warnAboutAccessingKey,
    configurable: true,
  });
}

function defineRefPropWarningGetter(props, displayName) {
  const warnAboutAccessingRef = function() {
    if (!specialPropRefWarningShown) {
      specialPropRefWarningShown = true;
      warningWithoutStack(
        false,
        '%s: `ref` is not a prop. Trying to access it will result ' +
          'in `undefined` being returned. If you need to access the same ' +
          'value within the child component, you should pass it as a different ' +
          'prop. (https://fb.me/react-special-props)',
        displayName,
      );
    }
  };
  warnAboutAccessingRef.isReactWarning = true;
  Object.defineProperty(props, 'ref', {
    get: warnAboutAccessingRef,
    configurable: true,
  });
}

/**
 * Factory method to create a new React element. This no longer adheres to
 * the class pattern, so do not use new to call it. Also, no instanceof check
 * will work. Instead test $$typeof field against Symbol.for('react.element') to check
 * if something is a React Element.
 *
 * @param {*} type
 * @param {*} key
 * @param {string|object} ref
 * @param {*} self A *temporary* helper to detect places where `this` is
 * different from the `owner` when React.createElement is called, so that we
 * can warn. We want to get rid of owner and replace string `ref`s with arrow
 * functions, and as long as `this` and owner are the same, there will be no
 * change in behavior.
 * @param {*} source An annotation object (added by a transpiler or otherwise)
 * indicating filename, line number, and/or other information.
 * @param {*} owner
 * @param {*} props
 * @internal
 */
const ReactElement = function(type, key, ref, self, source, owner, props) {
  const element = {
    // This tag allows us to uniquely identify this as a React Element
    $$typeof: REACT_ELEMENT_TYPE,

    // Built-in properties that belong on the element
    type: type,
    key: key,
    ref: ref,
    props: props,

    // Record the component responsible for creating this element.
    _owner: owner,
  };

  if (__DEV__) {
    // The validation flag is currently mutative. We put it on
    // an external backing store so that we can freeze the whole object.
    // This can be replaced with a WeakMap once they are implemented in
    // commonly used development environments.
    element._store = {};

    // To make comparing ReactElements easier for testing purposes, we make
    // the validation flag non-enumerable (where possible, which should
    // include every environment we run tests in), so the test framework
    // ignores it.
    Object.defineProperty(element._store, 'validated', {
      configurable: false,
      enumerable: false,
      writable: true,
      value: false,
    });
    // self and source are DEV only properties.
    Object.defineProperty(element, '_self', {
      configurable: false,
      enumerable: false,
      writable: false,
      value: self,
    });
    // Two elements created in two different places should be considered
    // equal for testing purposes and therefore we hide it from enumeration.
    Object.defineProperty(element, '_source', {
      configurable: false,
      enumerable: false,
      writable: false,
      value: source,
    });
    if (Object.freeze) {
      Object.freeze(element.props);
      Object.freeze(element);
    }
  }

  return element;
};

/**
 * Create and return a new ReactElement of the given type.
 * See https://reactjs.org/docs/react-api.html#createelement
 */
export function createElement(type, config, children) {
  let propName;

  // Reserved names are extracted
  const props = {};

  let key = null;
  let ref = null;
  let self = null;
  let source = null;

  if (config != null) {
    if (hasValidRef(config)) {
      ref = config.ref;
    }
    if (hasValidKey(config)) {
      key = '' + config.key;
    }

    self = config.__self === undefined ? null : config.__self;
    source = config.__source === undefined ? null : config.__source;
    // Remaining properties are added to a new props object
    for (propName in config) {
      if (
        hasOwnProperty.call(config, propName) &&
        !RESERVED_PROPS.hasOwnProperty(propName)
      ) {
        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];
    }
    if (__DEV__) {
      if (Object.freeze) {
        Object.freeze(childArray);
      }
    }
    props.children = childArray;
  }

  // Resolve default props
  if (type && type.defaultProps) {
    const defaultProps = type.defaultProps;
    for (propName in defaultProps) {
      if (props[propName] === undefined) {
        props[propName] = defaultProps[propName];
      }
    }
  }
  if (__DEV__) {
    if (key || ref) {
      const displayName =
        typeof type === 'function'
          ? type.displayName || type.name || 'Unknown'
          : type;
      if (key) {
        defineKeyPropWarningGetter(props, displayName);
      }
      if (ref) {
        defineRefPropWarningGetter(props, displayName);
      }
    }
  }
  return ReactElement(
    type,
    key,
    ref,
    self,
    source,
    ReactCurrentOwner.current,
    props,
  );
}

/**
 * Return a function that produces ReactElements of a given type.
 * See https://reactjs.org/docs/react-api.html#createfactory
 */
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 it
  factory.type = type;
  return factory;
}

export function cloneAndReplaceKey(oldElement, newKey) {
  const newElement = ReactElement(
    oldElement.type,
    newKey,
    oldElement.ref,
    oldElement._self,
    oldElement._source,
    oldElement._owner,
    oldElement.props,
  );

  return newElement;
}

/**
 * Clone and return a new ReactElement using element as the starting point.
 * See https://reactjs.org/docs/react-api.html#cloneelement
 */
export 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 copied
  const props = Object.assign({}, element.props);

  // Reserved names are extracted
  let 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 overridden
  let 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 props
    let 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 props
          props[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);
}

/**
 * Verifies the object is a ReactElement.
 * See https://reactjs.org/docs/react-api.html#isvalidelement
 * @param {?object} object
 * @return {boolean} True if `object` is a ReactElement.
 * @final
 */
export function isValidElement(object) {
  return (
    typeof object === 'object' &&
    object !== null &&
    object.$$typeof === REACT_ELEMENT_TYPE
  );
}
  • 在这个文件里面先找到 createElement 这个方法,我们可以看到它接收的三个参数
    • type
      • 就是我们的节点类型,如果是原生的节点,那么它是一个字符串
      • 那如果是我们自己声明的组件,它就是一个class component 或者是一个 functional component
      • 还会有其他的一些情况。比如 使用 React 原生的一些组件
        • 比如说 Fragment、 StrictMode、 Suspense
        • 这些都是 React 提供我们的一些原生组件,
        • 其实,上面三个它们默认就只是一个 Symbol
        • 它没有任何其他的功能,就仅仅是一个标志
    • config
      • 是我们写在这个JSX标签上面的所有的 attributes
      • 它们都会变成key value的形式存到这个config对象里面
      • 我们要从这个对象里面筛选出真正的props的内容
      • 还有特殊的,比如说 key,ref 这些属性
    • children
      • 就是我们标签中间我们放的一些内容
      • 它可能是一个子标签,或者它直接是文字 text
  • 我们来看一下它如何去创建一个 ReactElement, 还是回到 createElement 这个方法
    • 内部声明了一堆变量,找到有没有合理的REF,有没有合理的key
    • 我们把这些都给它读到一个单独的变量里面
    • 忽略 self 和 source 这两个东西,不是特别的重要
    • 接下去,要对剩下的config下面的 props 进行一个处理
      • 判断一下它是否是内建的 props,如果不是的话,就放到一个新建的 props 对象里面
      • 如果是内建的 props,就不放进去了,因为它不属于正常的 props 的范畴
      • 看一下这个内建的 props,它是什么东西
        const RESERVED_PROPS = {
          key: true,
          ref: true,
          __self: true,
          __source: true,
        };
        
      • key, ref, __self, __source, 这些都不会出现在我们使用class component 的场景下
        • 比如说我们的 this.props里面
        • 因为在处理props的过程当中,就已经把它处理掉了
    • 这边把 props 的属性全部拿出来,放到一个新的对象里面之后
    • 接下去要处理children
      • children 是可以有多个的,在一个节点下面
      • 它的 children 可能有很多的兄弟节点存在
      • 它是作为后续的参数传进来的,虽然在声明 createElement的时候只有三个参数
      • 但是它是可以传 3,4,5,6,7,8,9, … 多个参数的
      • 后续第三个参数之后的参数,我们都认为它们是 children
      • 在react当中把后续 arguments.length - 2 代表剩下的这个长度都是children
      • 然后会一个一个把它读出来,然后变成一个数组
      • 声明一个数组, 存放后续所有的 children 节点对象, 最终再把它放到 props.children
      • 通过 this.props.children 拿到的就是这部分的内容
    • 接下来,就是 defaultProps 的处理
      • 在声明 class Comp 的时候,比如说我们 extends React.Component
      • 我们可以通过 Comp.defaultProps 一个对象,给接收的这些props去设置一些默认值
      • 比如说, 这边它的默认值是 {value:1},当组件在被使用的时候,没有传value这个props
      • 在这里面就会使用 1 作为我们在组件内部 this.props.value 去拿到的这个值
      • 它就是把我们刚才上面处理过的那个props对象上面去读取对应的defaultProps里面的每一个key的值
      • 如果值是 undefined,就把它设置为 defaultProps 里面的属性
      • 如果它是有值的, 我们就不设置了
      • 注意
        • 它的判断条件是 undefined
        • 也就是说 null 也是一个不需要使用默认值的情况
    • 接着,下面 DEV 判断的代码,进行忽略
    • 最终 return了一个 ReactElement
      • 传入刚才处理过的这些内容
  • 关于 ReactElement
    • 它不是一个 class Comp, 而是一个 function
    • 最终会return一个Object, 这个Object也就几个主要的属性
      • $$typeof 是 REACT_ELEMENT_TYPE
        • 是用来标识我们的 element 是什么类型的
        • 在写JSX代码的时候,所有的节点都是通过 createElement 进行创建的
        • 那么,它的 $$typeof 永远都是 REACT_ELEMENT_TYPE
        • 在后续React的更新渲染dom的过程中是经常被用到的
        • 大部分情况下,我们拿到的 $$typeof 都是 REACT_ELEMENT_TYPE
        • 有一些特殊情况是和平台相关
          • 在react-dom里面,它有一个API叫做 React.createPortal, 它返回的对象和这里的类似
          • 但是它的 $$typeof 是 REACT_PORTAL_TYPE
      • type 是之前传进来的那个 type
        • 是在 createElement 的时候接收的那个 type
        • 用于记录节点的类型,是原生组件,还是 class Comp
      • key 就是上面处理过的 key
      • ref 就是 ref
      • props 就是 props
    • 综上,就是一个 ReactElement, 具体的方法,如何去操作,以及最终返回的类型
React 源码阅读入门1(JSX与Component) 基本信息 React的github地址 可选择分支对应的版本进行克隆。此处使用当前的master分支既v16.12.0进行学习。 项目目录结构如下,最重要的react与react-dom源码,位于package文件夹下对应目录的src文件夹中。 react源码的目录结构 react/src/React.js 创建React对象,该对象包括我们平时开发中常用的react api,例如C... 阅读详情

相关推荐

react源码分析:babel如何解析jsx

不管是类组件还是函数组件,最终我们写的jsx都被babel转化成了可识别的元素,其中我们也看了Component等内部实现,了解到了作为他是怎么被创建的,但是远远没有完,因为我们知道我们在写React的时候,会在后面带上一个,没错我们下一章节就要去探索一下方法了。一章我想跟大家探讨的是React的生命周期与事件系统。这一章主要是介绍组件在mountupdatedestroy阶段的生命周期执行顺序与React事件系统的注册,绑定,调度更新等。

weixin_59558923的博客 682

从零开始学习React:了解组件的三大属性

从零开始学习React:了解当前React常用技术,编写第一个React组件 从零开始学习React:了解组件的三大属性 上一节我们简单介绍了React的相关技术栈,以及如何在一个 html 文件中使用 React,创建一个React 组件并渲染到Html 中。 本节我们来介绍在 React 中 一个组件比较重要的三大属性 组件三大属性 就如我们上一节中介绍的一个最简单的函数式组件是这样的: const H2 = ({ title }) => <h2>{title}</h2&gt

Junerver的博客 667

基于 AUTOSAR 的域控产品软件开发进阶探索

本文深入探讨了AUTOSAR架构在汽车域控产品开发中的进阶应用。首先从系统设计角度分析了AUTOSAR分层架构原理及其在域控产品中的优化部署策略;其次详细介绍了Davinci和EBTresos等主流工具链的特点与协同使用方法;然后重点阐述了ASPICE流程与功能安全/信息安全标准的实施要点;最后分享了多核车载芯片(如NXP S32G)的适配经验与优化实践。通过架构设计、工具运用、标准遵循和芯片适配四个维度的专业解析,为域控产品的AUTOSAR开发提供了系统性指导。

SiArch的博客 1201

React源码解毒 - 检测开发者是否错误的使用了props属性

对props的错误使用是在开放环境下生效的,在createElement 方法相应的处理逻辑中,它先判断是否当前处于开发环境中,是则判断key或者ref是否存在,如果存在,则调用相对应的处理方法,通过为props的key或者ref属性设置getter侦听器,来实现对props中错误使用key或ref的错误提示,当你尝试通过props.key 或者props.ref 来获取相应属性的时候,就给你在控制台中报出相应组件的错误使用提示。

前端高薪进击手记 1534

Power BI常见问题篇1:无法打开文档

Power BI常见问题篇1:无法打开文档

weixin_48273257的博客 3307

无人驾驶汽车系统入门(三十二)——FEC算法:点云快速欧几里得聚类实战解析

本文深入解析了FEC算法在无人驾驶点云聚类中的高效应用,通过逐点处理策略和体素栅格预分割技术,实现了比传统欧几里得聚类快百倍的速度。文章详细介绍了算法原理、Python实现及参数调优指南,并对比了FEC与传统算法的性能差异,为无人驾驶系统开发提供了实用解决方案。

weixin_29065015的博客 488

基于Arduino与WS2812B打造光影时钟:从电路设计到代码实现

在嵌入式系统与物联网应用中,微控制器作为核心控制单元,通过编程实现对周边设备的精准操控。其工作原理在于接收输入信号,执行预设逻辑,并驱动执行器完成特定功能。这种技术价值在于将抽象的逻辑转化为具体的物理交互,极大地拓展了电子产品的创意边界。在智能家居、个性化装饰及教育实践等领域,基于开源硬件平台的项目尤为常见。例如,利用可编程LED灯带实现动态视觉效果,结合间接照明原理,可以创造出既实用又具艺术感的装置。本文聚焦于如何运用Arduino平台与WS2812B可寻址LED灯带,构建一个通过墙面光晕投影来显示时间的

weixin_33709364的博客 707

保姆级教程:在Ubuntu 22.04上用Conda搞定nuPlan数据集环境(Python 3.9 + PyTorch)

本文提供了一份详细的Ubuntu 22.04环境下使用Conda配置nuPlan自动驾驶数据集的保姆级教程,涵盖Python 3.9安装、Conda环境管理、PyTorch配置及数据集可视化验证等关键步骤,帮助开发者高效搭建开发环境。

weixin_29061997的博客 257

React 深度学习:3. ReactElement

ReactElement 下面导出了多个方法:createElement 用于创建并返回一个新的ReactElement 元素createFactory 用于返回固定类的createElement方法 【已废弃】cloneElement克隆一个元素isValidElement验证一个对象是否为 ReactElement 。cloneAndReplaceKey使用给定 key返回...

weixin_33840661的博客 1723

Applied Intelligence投稿经验分享(正在投稿中)

这几天在投稿Applied Intelligence这个期刊,过程很曲折,反反复复,因此写一篇经验分享,希望能记录一下自己的过程,也能给其他人一些帮助(可以在评论区讨论),提醒一下,一定要写一些声明,不会写、不知道写啥就看第四章的第二个问题。

weixin_55988068的博客 1万+

告别 RPA 和 Selenium,MCP + Playwright 成为自动化开发新宠!

摘要: 随着数字化转型加速,传统自动化工具(如RPA和Selenium)在复杂场景中暴露出开发成本高、灵活性不足等问题。新一代解决方案MCP(Model Context Protocol)与Playwright的结合,通过AI与自动化的无缝对接,实现了智能化的任务处理。MCP支持自然语言交互和上下文感知,开发者无需编写复杂代码即可生成自动化脚本;Playwright则提供多浏览器支持、高性能和易用性。二者结合显著提升开发效率,使自动化更智能、灵活。文章还对比了VS Code与Trae中配置Playwrigh

我先测了 2211

React笔记整理

大概大半年时间都在用react写项目,一直在笔记上零零星星地记录着,在新的一年即将到来之际,打算整理整理发出来。 一、React是什么? React是Facebook开源的用于构建用户界面的javascript库。(好些人都觉着React很神秘,接触新事物时,一定要把它看得简单,这样你才有信心战胜它啊,其实入门真的不难) 二、React的特点即它与其他js库相比好在哪里? 1、专...

azywc291549的博客 1266

ArcGISPro应用指南:ArcGISPro制图全流程详解

本文介绍了基于ArcGIS Pro的地图制作基本流程,旨在帮助读者快速掌握从数据加载到地图输出的完整制图操作。文章首先简要概述了GIS技术在当今数据驱动时代的重要作用,并引出ArcGIS Pro作为专业GIS平台的优势与应用价值。随后,内容围绕地图制作的核心步骤展开,包括数据加载、布局创建、地图范围设置以及各类地图要素(如指北针、比例尺、图例、图名)的插入与样式调整。此外,还介绍了如何通过添加图形、文本及动态元素增强地图表达效果,并最终完成地图导出设置与文件输出格式的选择。

weixin_45812624的博客 1361

前端战五渣学React——JSX & React.createElement() & React.ReactElement()源码

最近《一拳超人》动画更新第二季了,感觉打斗场面没有第一季那么烧钱了,但是剧情还挺好看的,就找了漫画来看。琦玉老师真的厉害!!!打谁都一拳,就喜欢看老师一拳把那些上来就吹牛逼的反派打的稀烂,专治各种不服!!! 招聘AD 阿里巴巴集团核心前端岗位 薪资25到50 一年一般至少16个月工资 有意者微信联系:Dell-JS 正文 三大民工框架 说到现在的前端,各种招聘JD上都会写 “对主流框架(Re...

weixin_33772645的博客 467

基于物联网技术设计的微型消防小车控制系统(STM32+ESP8266局域网)(181)

基于物联网技术的小微型消防车控制系统。通过远程控制功能,用户能够灵活操作消防车的行驶,方便快速抵达火灾现场。环境感知功能实时采集烟雾浓度、温湿度信息,为灭火决策提供科学依据。火源定位功能采用自动和手动两种模式,准确迅速地定位火源,并通过报警提示用户。灭火功能则根据火源定位结果,自动或手动启动干粉灭火器进行高效灭火。这些功能的结合实现了对小型火灾的全面应对,提升了消防效率与安全性,减少了火灾带来的损失。通过本项目的设计与实现,为消防领域提供了一种创新且实用的解决方案。

3083

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

react实现div隐藏_前端战五渣学React——JSX & React.createElement()源码

最近《一拳超人》动画更新第二季了,感觉打斗场面没有第一季那么烧钱了,但是剧情还挺好看的,就找了漫画来看。琦玉老师真的厉害!!!打谁都一拳,就喜欢看老师一拳把那些上来就吹牛逼的反派打的稀烂,专治各种不服!!!招聘AD阿里巴巴集团核心前端岗位薪资25到50一年一般至少16个月工资有意者微信联系:Dell-JS正文三大民工框架说到现在的前端,各种招聘JD上都会写“对主流框架(React/Vue/Ang...

weixin_33967069的博客 439

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: React16源码: Why16, 研究源码的意义, 源码目录核心结构分析
下一篇: React16源码: Component与PureComponent源码实现
Wang's Blog
博客等级 码龄12年 7438粉丝 2421原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wang's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值