React源码学习:JSX 与 React.createElement 相关的知识
2.2 深入理解JSX.mp4
jsx 与 React.createElement
关系
- https://babeljs.io/repl
- Jsx 与 React.createElement 一一对应
<h1 model={{ role:'header' }}>
it works
<img title="logo" src="https://js.work/logo.png" />
</h1>
"use strict";
/*#__PURE__*/
React.createElement("h1", {
model: {
role: 'header'
}
}, "it works", /*#__PURE__*/React.createElement("img", {
title: "logo",
src: "https://js.work/logo.png"
}));
看源码:
- 目录:
/Users/aric.zheng/github/react/packages/react/src/React.js
- 位置:const createElement = __DEV__ ?
createElementWithValidation
: createElementProd - /Users/aric.zheng/github/react/packages/shared/isValidElementType.js
- 最终核心文件是这个:/Users/aric.zheng/github/react/packages/
react/src/ReactElement.js
export default function isValidElementType(type: mixed) {
if (typeof type === 'string' || typeof type === 'function') {
return true;
}
// Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
if (
type === REACT_FRAGMENT_TYPE ||
type === REACT_PROFILER_TYPE ||
type === REACT_DEBUG_TRACING_MODE_TYPE ||
type === REACT_STRICT_MODE_TYPE ||
type === REACT_SUSPENSE_TYPE ||
type === REACT_SUSPENSE_LIST_TYPE ||
type === REACT_LEGACY_HIDDEN_TYPE ||
(enableScopeAPI && type === REACT_SCOPE_TYPE)
) {
return true;
}
if (typeof type === 'object' && type !== null) {
if (
type.$$typeof === REACT_LAZY_TYPE ||
type.$$typeof === REACT_MEMO_TYPE ||
type.$$typeof === REACT_PROVIDER_TYPE ||
type.$$typeof === REACT_CONTEXT_TYPE ||
type.$$typeof === REACT_FORWARD_REF_TYPE ||
type.$$typeof === REACT_FUNDAMENTAL_TYPE ||
type.$$typeof === REACT_BLOCK_TYPE ||
type[(0: any)] === REACT_SERVER_BLOCK_TYPE
) {
return true;
}
}
return false;
}
几个受保护的 props
const RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true,
};
ReactElement
这个就是我们经常看到的
ReactElement
类型了
export let REACT_ELEMENT_TYPE = 0xeac7;
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,
};
return element;
};