前言

众所周知React Native开发中,页面View书写布局采用了React 的JSX语法,而在ReactNative面试中可能会遇到有关JSX相关的面试题,今天和大家分享有关JSX的知识,为你的面试助一臂之力。

JSX的定义

JSX到底是什么?我们先看看[React官网](https://reactjs.org/docs/glossary.html#jsx)的定义。

JSX is a syntax extension to JavaScript. It is similar to a template

language, but it has full power of JavaScript. JSX gets compiled to

React.createElement() calls which return plain JavaScript objects

called “React elements”.

JSX是JavaScript的一种语法扩展,类似一种模板语言,但是它拥有JavaScript的全部能力。JSX被编译成React.createElement(), React.createElement()返回一个名为“React element”的JavaScript对象。

从以上定义可以看到JSX是作为一种扩展存在的,那就会出现在低版本的浏览器或者其他开发环境中的兼容性问题。怎么解决这个问题呢?上面定义中也提到了, JSX被编译成React.createElement()并返回一个js对象。

JSX编译工具-Babel

将JSX编译成js对象就是由Babel完成的。

[Babel官网](https://babeljs.io/docs/en/)的定义:

Babel是一个工具链,主要用于将ECMAScript 2015+代码转换为当前和旧版本浏览器或环境中向后兼容的JavaScript版本。

比如在ES2015中出现的箭头函数,转成ES5环境的支持

// Babel Input: ES2015 arrow function[1, 2, 3].map((n) => n + 1);

// Babel Output: ES5 equivalent[1, 2, 3].map(function(n) {return n + 1;});

类似的,Babel也可以编译JSX语法。

Babel can convert JSX syntax! Check out our React preset to get

started. Use it together with the babel-sublime package to bring

syntax highlighting to a whole new level.

如下一段代码是ReactNative经典的入门Hello World.

import React from 'react';import { Text, View } from 'react-native';

const HelloWorldApp = () => {return (style={{flex: 1,justifyContent: "center",alignItems: "center"}}>Hello, world!Text>View>)}export default HelloWorldApp;

我们将布局文件使用[Babel工具]编译一下,看看编译后的代码是什么样子的

从编译结果可以看到,所有的JSX标签都被编译成了React.createElement调用了,所以我们书写JSX其实就是在写React.createElement()函数调用

JSX描述小结

JSX的正确描述应该是它是JavaScript调用函数React.createElement()的语法糖。

为什么React使用JSX

在上面分析中我们看到通过Babel转换JSX后其实就是React.createElement的调用,为什么我们不直接使用React.createElement,而要使用JSX语法糖呢?

其实从上面Babel编译截图上可以看到,布局中只有两个元素View,Text,直接写React.createElement的代码就很多了,如果是很多元素的嵌套,那画面没法想象了,首先代码阅读体验不好,布局的嵌套也非常的混乱。相比较而言JSX就显得层次分明,嵌套关系清晰。

结论:使用JSX语法糖可以使用开发人员使用类Html的标签创建虚拟DOM进行布局,既提高了开发效率和体验,也降低了学习成本。

JSX是如何映射为虚拟DOM的

我们已经知道了JSX会通过Babel编译成React.createElement()调用,我们看一下这个方法的源码实现:

function createElement(type, config, children) {var propName = void 0;

// Reserved names are extractedvar props = {};

var key = null;var ref = null;var self = null;var source = null;

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;// Remaining properties are added to a new props objectfor (propName in config) {if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {props[propName] = config[propName];}}}

// Children can be more than one argument, and those are transferred onto// the newly allocated props object.var childrenLength = arguments.length - 2;if (childrenLength === 1) {props.children = children;} else if (childrenLength > 1) {var childArray = Array(childrenLength);for (var i = 0; i < childrenLength; i++) {childArray[i] = arguments[i + 2];}{if (Object.freeze) {Object.freeze(childArray);}}props.children = childArray;}

// Resolve default propsif (type && type.defaultProps) {var defaultProps = type.defaultProps;for (propName in defaultProps) {if (props[propName] === undefined) {props[propName] = defaultProps[propName];}}}{if (key || ref) {var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;if (key) {defineKeyPropWarningGetter(props, displayName);}if (ref) {defineRefPropWarningGetter(props, displayName);}}}return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);}

通过以上源码我们可以看到createElement函数接受三个参数,分别是type, config, childen。

  • type:标识节点的类型。可以是标记名字符串(例如'div'或'span')、React组件类型(类或函数)或React片段类型。

  • config: 组件的所有属性以键值对的形式存储在config中,以对象的形式传递。

  • childen: 组件的嵌套内容,也就是子元素,子节点,也是以对象的形式进行传递。

createElement函数主要做了如下工作:

  1. 根据config,处理key, ref, self, source的赋值工作

  2. 遍历config,刷选适合的属性放入到props中

  3. 获取子元素放入到children中

  4. 处理defaultProps

  5. 最终调用ReactElement来创建元素。

如何渲染到DOM

ReactElement是通过React.render()方法渲染到DOM。

下面是一个示例

const element =Hello, worldh1>;ReactDOM.render(element, document.getElementById('root'));

render()

ReactDOM.render(element, container[, callback])

ReactDOM.render函数接受三个参数,第一个是代表元素或者节点,第二个container是一个真是的DOM节点,作为一个DOM容器,用于包含渲染的元素内容。

总结

JSX只是一种语法糖,你也可以不使用JSX进行书写页面布局,但是使用JSX会使页面布局层次分明,嵌套逻辑清晰,方便前端开发人员使用熟悉的类Html标签进行开发,调高了开发体验和效率,并且也提供了更多有用错误和警告信息。

通过以上内容,相信面试的时候遇到此类问题,一定可以回答的比较深入了。

--- END ---

君伟说