c君不在

2018/10/07

React 的行内条件渲染(inline conditional rendering)能够在无 else 分支的情况下简化条件渲染,这是由子元素定义及渲染决定的。

const ele = (
  <div>
    <p>{true}</p>
    <p>{true && 1}</p>

    <p>{false}</p>
    <p>{false && 2}</p>
  </div>
);

对应的 JavaScript 代码是

const ele = React.createElement(
  "div",
  null,
  React.createElement("p", null, true),
  React.createElement("p", null, true && 1),
  React.createElement("p", null, false),
  React.createElement("p", null, false && 2)
);

true && 1 等的表达式结果作为子元素去渲染时,使用  ChildReconciler#createChild ,其中仅当子元素类型(typeof)是 stringnumberobject 且不为 null 时才渲染,所以 true / false 则不会渲染。

function createChild(
  returnFiber: Fiber,
  newChild: any,
  expirationTime: ExpirationTime,
): Fiber | null {
  if (typeof newChild === 'string' || typeof newChild === 'number') {
    // Text nodes don't have keys. If the previous node is implicitly keyed
    // we can continue to replace it without aborting even if it is not a text
    // node.
    const created = createFiberFromText(
      '' + newChild,
      returnFiber.mode,
      expirationTime,
    );
    created.return = returnFiber;
    return created;
  }

  if (typeof newChild === 'object' && newChild !== null) {
    switch (newChild.$$typeof) {
      case REACT_ELEMENT_TYPE: {
        const created = createFiberFromElement(
          newChild,
          returnFiber.mode,
          expirationTime,
        );
        created.ref = coerceRef(returnFiber, null, newChild);
        created.return = returnFiber;
        return created;
      }
      case REACT_PORTAL_TYPE: {
        const created = createFiberFromPortal(
          newChild,
          returnFiber.mode,
          expirationTime,
        );
        created.return = returnFiber;
        return created;
      }
    }

    if (isArray(newChild) || getIteratorFn(newChild)) {
      const created = createFiberFromFragment(
        newChild,
        returnFiber.mode,
        expirationTime,
        null,
      );
      created.return = returnFiber;
      return created;
    }

    throwOnInvalidObjectType(returnFiber, newChild);
  }

  if (__DEV__) {
    if (typeof newChild === 'function') {
      warnOnFunctionType();
    }
  }

  return null;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注