React 与 Babel
元素标签转译
用过 React 的同学都晓得,当咱们这样写时:
<div id="foo">bar</div>
Babel 会将其转译为:
React.createElement("div", {id: "foo"}, "bar");
咱们会发现,createElement
的第一个参数是元素类型,第二个参数是元素属性,第三个参数是子元素
组件转译
如果咱们用的是一个组件呢?
function Foo({id}) { return <div id={id}>foo</div>}<Foo id="foo"> <div id="bar">bar</div></Foo>
Babel 则会将其转译为:
function Foo({id}) { return React.createElement("div", {id: id}, "foo")}React.createElement(Foo, {id: "foo"}, React.createElement("div", {id: "bar"}, "bar"));
咱们会发现,createElement
的第一个参数传入的是变量 Foo
子元素转译
如果咱们有多个子元素呢?
<div id="foo"> <div id="bar">bar</div> <div id="baz">baz</div> <div id="qux">qux</div></div>
Babel 则会将其转译为:
React.createElement("div", { id: "foo"}, React.createElement("div", {id: "bar"}, "bar"), React.createElement("div", {id: "baz"}, "baz"), React.createElement("div", {id: "qux"}, "qux"));
咱们会发现,子元素其实是作为参数一直追加传入到函数中
createElement
那 React.createElement 到底做了什么呢?
源码
咱们查看 React 的 GitHub 仓库:https://github.com/facebook/react,查看 pacakges/react/index.js
文件,能够看到 createElement
的定义在 ./src/React
文件:
// 简化后export {createElement} from './src/React';
咱们关上 ./src/React.js
文件:
import { createElement as createElementProd} from './ReactElement';const createElement = __DEV__ ? createElementWithValidation : createElementProd;export { createElement };
持续查看 ./ReactElement.js
文件,在这里终于找到最终的定义,鉴于这里代码较长,咱们将代码极度简化一下:
const RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true,};export function createElement(type, config, ...children) { let propName; // Reserved names are extracted const props = {}; // 第一段 let key = '' + config.key; let ref = config.ref; let self = config.__self; let source = config.__source; // 第二段 for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } // 第三段 props.children = children; // 第四段 if (type && type.defaultProps) { const defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } // 第五段 return ReactElement( type, key, ref, self, source, ReactCurrentOwner.current, props, );}
这里能够看出,createElement
函数次要是做了一个预处理,而后将解决好的数据传入 ReactElement
函数中,咱们先剖析下 createElement 做了什么。
函数入参
咱们以最一开始的例子为例:
<div id="foo">bar</div>// 转译为React.createElement("div", {id: "foo"}, "bar");
对于createElement
的三个形参,其中type
示意类型,既能够是标签名字符串(如 div 或 span),也能够是 React 组件(如 Foo)
config
示意传入的属性,children
示意子元素
第一段代码 __self 和 __source
当初咱们开始看第一段代码:
// 第一段 let key = '' + config.key; let ref = config.ref; let self = config.__self; let source = config.__source;
能够看到在 createElement
函数外部,key
、ref
、__self
、__source
这四个参数是独自获取并解决的,key
和 ref
很好了解,__self
和 __source
是做什么用的呢?
通过这个 issue,咱们理解到,__self
和 __source
是 babel-preset-react
注入的调试信息,能够提供更有用的错误信息。
咱们查看 babel-preset-react 的文档,能够看到:
development
boolean 类型,默认值为 false.
这能够用于开启特定于开发环境的某些行为,例如增加 __source 和 __self。
在与 env 参数 配置或 js 配置文件 配合应用时,此性能很有用。
如果咱们试着开启 development
参数,就会看到 __self
和 __source
参数,仍然以 <div id="foo">bar</div>
为例,会被 Babel 转译成:
var _jsxFileName = "/Users/kevin/Desktop/react-app/src/index.js";React.createElement("div", { id: "foo", __self: this, __source: { fileName: _jsxFileName, lineNumber: 5, columnNumber: 13 }}, "bar");
第二段代码 props 对象
当初咱们看第二段代码:
// 第二段for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; }}
这段代码实现的性能很简略,就是构建一个 props 对象,去除传入的 key
、ref
、__self
、__source
属性,这就是为什么在组件中,咱们明明传入了 key
和ref
,但咱们无奈通过 this.props.key
或者 this.props.ref
来获取传入的值,就是因为在这里被去除掉了。
而之所以去除,React 给出的解释是,key
和 ref
是用于 React 外部解决的,如果你想用比方 key 值,你能够再传一个其余属性,用跟 key 雷同的值即可。
第三段代码 children
当初咱们看第三段代码,这段代码被精简的很简略:
// 第三段props.children = children;
这是其实是因为咱们为了简化代码,用了 ES6 的扩大运算法,理论的源码里会简单且有一些差异:
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;}
咱们也能够发现,当只有一个子元素的时候,children
其实会间接赋值给 props.children
,也就是说,当只有一个子元素时,children 是一个对象(React 元素),当有多个子元素时,children 是一个蕴含对象(React 元素)的数组。
第四段代码 defaultProps
当初咱们看第四段代码:
// 第四段 if (type && type.defaultProps) { const defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } }
这段其实是解决组件的defaultProps
,无论是函数组件还是类组件都反对 defaultProps
,举个应用例子:
// 函数组件function Foo({id}) { return <div id={id}>foo</div>} Foo.defaultProps = { id: 'foo' }// 类组件 class Header extends Component { static defaultProps = { id: 'foo' } render () { const { id } = this.props return <div id={id}>foo</div> } }
第五段代码 owner
当初咱们看第五段代码:
// 第五段 return ReactElement( type, key, ref, self, source, ReactCurrentOwner.current, props, );
这段就是把后面解决好的 type
、key
等值传入 ReactElement
函数中,那 ReactCurrentOwner.current
是个什么鬼?
咱们依据援用地址查看 ReactCurrentOwner
定义的文件:
/** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */const ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null,};export default ReactCurrentOwner;
其初始的定义非常简单,依据正文,咱们能够理解到 ReactCurrentOwner.current
就是指向处于构建过程中的组件的 owner,具体作用在当前的文章中还有介绍,当初能够简略的了解为,它就是用于记录长期变量。
ReactElement
源码
当初咱们开始看 ReactElement 函数,其实这个函数的内容更简略,代码精简后如下:
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;};
如你所见,它就是返回一个对象,这个对象包含 $$typeof
、type
、key
等属性,这个对象就被称为 “React 元素”。它形容了咱们在屏幕上看到的内容。React 会通过读取这些对象,应用它们构建和更新 DOM
REACT_ELEMENT_TYPE
而 REACT_ELEMENT_TYPE
查看援用的 packages/shared/ReactSymbols
文件,能够发现它就是一个惟一常量值,用于标示是 React 元素节点
export const REACT_ELEMENT_TYPE = Symbol.for('react.element');
那还有其余类型的节点吗? 查看这个定义 REACT_ELEMENT_TYPE
的文件,咱们发现还有:
export const REACT_PORTAL_TYPE: symbol = Symbol.for('react.portal');export const REACT_FRAGMENT_TYPE: symbol = Symbol.for('react.fragment');export const REACT_STRICT_MODE_TYPE: symbol = Symbol.for('react.strict_mode');export const REACT_PROFILER_TYPE: symbol = Symbol.for('react.profiler');export const REACT_PROVIDER_TYPE: symbol = Symbol.for('react.provider');export const REACT_CONTEXT_TYPE: symbol = Symbol.for('react.context');// ...
你可能会天然的了解为 $$typeof
还能够设置为 REACT_FRAGMENT_TYPE
等值。
咱们能够写代码试验一下,比方应用 Portal,打印一下返回的对象:
import ReactDOM from 'react-dom/client';import {createPortal} from 'react-dom'const root = ReactDOM.createRoot(document.getElementById('root'));function Modal() { const portalObject = createPortal(<div id="foo">foo</div>, document.getElementById("root2")); console.log(portalObject) return portalObject}root.render(<Modal />);
打印的对象为:
它的 $$typeof
的确是 REACT_PORTAL_TYPE
而如果咱们应用 Fragment
:
import ReactDOM from 'react-dom/client';import React from 'react';const root = ReactDOM.createRoot(document.getElementById('root'));function Modal() { const fragmentObject = ( <React.Fragment> <div id="foo">foo</div> </React.Fragment> ); console.log(fragmentObject) return fragmentObject}root.render(<Modal />);
打印的对象为:
咱们会发现,当咱们应用 fragment
的时候,返回的对象的 $$typeof
却仍然是 REACT_ELEMENT_TYPE
这是为什么呢?
其实细想一下咱们应用 portals 的时候,咱们用的是 React.createPortal
的形式,但 fragments
走的仍然是一般的 React.createElement
办法,createElement
的代码咱们也看到了,并无非凡解决 $$typeof
的中央,所以天然是 REACT_ELEMENT_TYPE
那么 $$typeof
到底是为什么存在呢?其实它次要是为了解决 web 平安问题,试想这样一段代码:
let message = { text: expectedTextButGotJSON };// React 0.13 中有危险<p> {message.text}</p>
如果 expectedTextButGotJSON
是来自于服务器的值,比方:
// 服务端容许用户存储 JSONlet expectedTextButGotJSON = { type: 'div', props: { dangerouslySetInnerHTML: { __html: '/* something bad */' }, }, // ...};let message = { text: expectedTextButGotJSON };
这就很容易受到 XSS 攻打,尽管这个攻打是来自服务器端的破绽,但应用 React 咱们能够解决的更好。如果咱们用 Symbol 标记每个 React 元素,因为服务端的数据不会有 Symbol.for('react.element')
,React 就能够检测 element.$$typeof
,如果元素失落或者有效,则能够回绝解决该元素,这样就保障了安全性。
回顾
至此,咱们残缺的看完了 React.createElement
的源码,当初咱们再看 React 官网文档的这段:
以下两种示例代码齐全等效:
const element = ( <h1 className="greeting"> Hello, world! </h1>);const element = React.createElement( 'h1', {className: 'greeting'}, 'Hello, world!');
React.createElement() 会事后执行一些查看,以帮忙你编写无错代码,但实际上它创立了一个这样的对象:
// 留神:这是简化过的构造const element = { type: 'h1', props: { className: 'greeting', children: 'Hello, world!' }};
这些对象被称为 “React 元素”。它们形容了你心愿在屏幕上看到的内容。React 通过读取这些对象,而后应用它们来构建 DOM 以及放弃随时更新。
当初你对这段是不是有了更加深刻的意识?
React 系列
解说 React 源码、React API 背地的实现机制,React 最佳实际、React 的倒退与历史等,预计 50 篇左右,欢送关注
如果喜爱或者有所启发,欢送 star,对作者也是一种激励。