React 源码(二)JSX & createElement
2021-01-15 本文已影响0人
bowen_wu
概述
在使用 React 的时候,编辑的都是 JSX 文件,那么 JSX 文件是什么呢?其实在写 JSX 时,React 会将 JSX 翻译为 React.createElement
。即
<h1 className='hello'>Hello world!</h1>
等价于
React.createElement("h1", {
className: "hello"
}, "Hello world!");
React.createElement
export function createElement(type, config, children) {
let propName;
const props = {};
let key = null;
let ref = null;
let self = null;
let source = null;
// 从 config 中获取 props、key、ref、self 和 source
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;
for(propName in config) {
if(hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
// 获取 props 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];
}
props.children = childArray;
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); // ???
}
ReactElement
const ReactElement = function(type, key, ref, self, source, own, props) {
const element = {
$$typeof: REACT_ELEMENT_TYPE, // symbol REACT_ELEMENT_TYPE = 0xeac7 用于标识 React 元素
type: type,
key: key,
ref: ref,
props: props,
_owner: owner, // ???
}
return element;
}
可以看到,ReactElement 就是一个对象。
疑问
-
createElement
中的ReactCurrentOwner.current
是啥? -
ReactElement
中的_owner
作用?