经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JavaScript » 查看文章
ReactElement源码笔记
来源:cnblogs  作者:feshin  时间:2021/3/8 11:51:08  对本文有异议

ReactElement 源码笔记

ReactElement通过 createElement创建,调用该方法需要 传入三个参数:

  • type
  • config
  • children

type指代这个ReactElement 的类型

config指代这个ReactElement 的属性对象

children指代这个ReactElement 的子元素节点

  • 字符串比如 'div''p'代表原生DOM,称为HostComponent
  • Class 类型是我们继承自 Component 或者 PureComponent的组件,称为ClassComponent
  • 方法就是 function Component
  • 原生提供的 FragmentAsyncMode 等是 Symbol,会被特殊处理
  • TODO: 是否有其他的
  1. //源码位置: packages/react/src/ReactElement.js
  2. // createElement函数
  3. export function createElement(type, config, children){
  4. // 一、处理config
  5. // 1. 判断config是否为空
  6. // 2. 提取保留属性(key, ref, self, soure)
  7. // 3. 其余属性添加到新的props对象中
  8. for(propName in config){
  9. if(
  10. hasOwnProperty.call(config, propName)&&
  11. !RESERVED_PROPS.hasOwnProperty(propName)
  12. ){
  13. props[propName] = config[propName]
  14. }
  15. }
  16. // 二、处理children => props.children
  17. // (children可以超过一个),处理过后的children 被放入 props.children
  18. const childrenLength = arguments.length - 2;
  19. if (childrenLength === 1) {
  20. props.children = children;
  21. } else if (childrenLength > 1) {
  22. const childArray = Array(childrenLength);
  23. for (let i = 0; i < childrenLength; i++) {
  24. childArray[i] = arguments[i + 2];
  25. }
  26. props.children = childArray;
  27. }
  28. // 三、处理type的 defaultProps
  29. if(type && type.defaultProps) {
  30. const defaultProps = type.defaultProps;
  31. for (propName in defaultProps) {
  32. if(props[propName] === undefined) {
  33. props[propName] = defaultProps[propName]
  34. }
  35. }
  36. }
  37. // 四、返回一个ReactElement()函数
  38. return ReactElement(
  39. type,
  40. key,
  41. ref,
  42. self,
  43. source,
  44. ReactCurrentOwner.current,
  45. props,
  46. );
  47. }

注:type.defaultProps的由来:

  1. 定义一个ClassComponent: class Comp extends React.Component
  2. 可以为 Comp设置一个defaultProps: Comp.defaultProps = { value: 1 }
  1. //源码位置: packages/react/src/ReactElement.js
  2. // ReactElement 函数
  3. const ReactElement = function(type, key, ref, self, source, owner, props){
  4. const element = {
  5. // $$typeof用于标识 Element 是什么类型的
  6. $$typeof: REACT_ELEMENT_TYPE,
  7. // Built-in properties that belong on the element
  8. type: type,
  9. key: key,
  10. ref: ref,
  11. props: props,
  12. // Record the component responsible for creating this element.
  13. _owner: owner,
  14. }
  15. // _DEV_ 代码...
  16. return element;
  17. }

原文链接:http://www.cnblogs.com/feng-senzhang/p/14475918.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号