JSX

//在{}可以正常显示的数据  string num array
      message: "Hello World" ,//String
      number: 18, //array
      array: ["aa","bbb", 15],//array

      //在react不能正常显示 null undefined, boolean, 默认不显示
      test1: null,
      test2: undefined,
      test3:true

解决:可以转换成字符串

 {this.state.test1 + " "}
 null

对象不能作为jsx的子类

Babel的作用主要是转义jsx的代码
jsx是React.CreateElement(component, props,...children)的语法糖
参数1:type:
  当前reactElement类型,如果是标签类型就直接使用字符串表示,“div”。 
  如果是组件类型,直接使用组件名称
参数2:config:
 jsx属性在config中以对象的属性和值形式存储
参数3:children
  存放标签中的内容,以children数组形式存储

通过jsx - >bebal -> React.createElement()

const message1 = <h2>hello react </h2>
const message2 = React.createElement("h2", null, "hello react")

package- react-index -createElement

const createElement = __DEV__ ? createElementWithValidation : createElementProd;
根据是否为开发模式使用不同的函数

```css


export function createElementWithValidation(type, props, children) {
 //1. isValidElementType判断type类型是否规范,(string, function,ReactSymbol(REACT_LAZY_TYPE,REACT_FRAGMENT_TYPE等) 是属于规范的)
  const validType = isValidElementType(type);

  //2. 不符合输入类型,根据输入的其余类型undefined, object,null,或者为空,发出警告
  if (!validType) {
    let info = '';
    if (
      type === undefined ||
      (typeof type === 'object' &&
        type !== null &&
        Object.keys(type).length === 0)
    ) {
      info +=
        ' You likely forgot to export your component from the file ' +
        "it's defined in, or you might have mixed up default and named imports.";
    }

    const sourceInfo = getSourceInfoErrorAddendumForProps(props);
    if (sourceInfo) {
      info += sourceInfo;
    } else {
      info += getDeclarationErrorAddendum();
    }

    let typeString;
    if (type === null) {
      typeString = 'null';
    } else if (Array.isArray(type)) {
      typeString = 'array';
    } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
      typeString = `<${getComponentName(type.type) || 'Unknown'} />`;
      info =
        ' Did you accidentally export a JSX literal instead of a component?';
    } else {
      typeString = typeof type;
    }
 
    //3.如果是开发模式,就打印错误,
    if (__DEV__) {
      console.error(
        'React.createElement: type is invalid -- expected a string (for ' +
          'built-in components) or a class/function (for composite ' +
          'components) but got: %s.%s',
        typeString,
        info,
      );
    }
  }
 //4.重点! 根据传入值创建返回一个reactElement
  const element = createElement.apply(this, arguments);

  // The result can be nullish if a mock or a custom function is used.
  // TODO: Drop this when these are no longer allowed as the type argument.
  if (element == null) {
    return element;
  }

  // Skip key warning if the type isn't valid since our key validation logic
  // doesn't expect a non-string/function type and can throw confusing errors.
  // We don't want exception behavior to differ between dev and prod.
  // (Rendering will throw with a helpful message and as soon as the type is
  // fixed, the key warnings will appear.)
  if (validType) {
    for (let i = 2; i < arguments.length; i++) {
      validateChildKeys(arguments[i], type);
    }
  }

  if (type === REACT_FRAGMENT_TYPE) {
    validateFragmentProps(element);
  } else {
    validatePropTypes(element);
  }

  return element;
}
//config包含组件上的所有props,包括:事件、key、ref、各种属性
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;

//1.提取key、ref、self、source、prop,(key是可以优化React的渲染速度的,ref是可以获取到React渲染后的真实DOM节点的
//主要使用的方法是Object.getOwnPropertyDescriptor(obj, prop)方法返回指定对象上一个自有属性对应的属性描述符
  if (config != null) {
    if (hasValidRef(config)) {
      ref = config.ref;

      if (__DEV__) {
        warnIfStringRefCannotBeAutoConverted(config);
      }
    }
    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];
      }
    }
  }
//2.arguments.length - 2判断剩余的参数
//如果只有一个元素直接挂载到props.chilredn; 如果是多个元素需要放入数组,在挂载到children,这里如果是开发模式,可以冻结数组,提高性能
  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;
  }
// 3.当type为ReactSymbol,取出默认值,放到props里
  if (type && type.defaultProps) {
    const defaultProps = type.defaultProps;
    for (propName in defaultProps) {
      if (props[propName] === undefined) {
        props[propName] = defaultProps[propName];
      }
    }
  }
  //4.在开发模式下,如果type是函数式,堆key,ref添加一些警告
  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);
      }
    }
  }
  //5.返回ReactElement = function(type, key, ref, self, source, owner, props)
  return ReactElement(
    type,
    key,
    ref,
    self,
    source,
    ReactCurrentOwner.current,
    props,
  );
}

const ReactElement = function(type, key, ref, self, source, owner, props) {
  const element = {
    // This tag allows us to uniquely identify this as a React Element
    //,表示这是通过createElement创建的。在react中还有一种情况是通过ReactDOM.createPoratl()  创建,这时它的'$$typeof'为REACT_PORTAL_TYPE。
    $$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 = {};

//_store中添加了一个新的对象validated(可写入), element对象中添加了_self和_source属性(只读),最后冻结了element.props和element。 这样就解释了为什么我们在子组件内修改props是没有效果的,只有在父级修改了props后子组件才会生效
    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;
};

最后返回的element就是reactElement, 也就是传说中的虚拟DOM
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210331220408561.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDk1NDA1OQ==,size_16,color_FFFFFF,t_70#pic_center)



 

虚拟DOM通过ReactDOM.render映射到真实DOM


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值