跳到主要内容

JavaScript 环境

JavaScript 运行时

当使用 React Native 时,你的 JavaScript 代码将会在最多三种环境中运行

  • 在大多数情况下,React Native 将会使用 Hermes,一个为 React Native 优化的开源 JavaScript 引擎。
  • 如果 Hermes 被禁用,React Native 将会使用 JavaScriptCore,为 Safari 提供支持的 JavaScript 引擎。请注意,在 iOS 上,由于 iOS 应用中缺少可写可执行内存,JavaScriptCore 不使用 JIT。
  • 当使用 Chrome 调试时,所有 JavaScript 代码都在 Chrome 本身内部运行,通过 WebSockets 与原生代码通信。Chrome 使用 V8 作为其 JavaScript 引擎。

虽然这些环境非常相似,但你最终可能会遇到一些不一致性。最好避免依赖任何运行时的特定细节。

JavaScript 语法转换器

语法转换器通过允许你使用新的 JavaScript 语法,而无需等待所有解释器的支持,从而使编写代码更加愉快。

React Native 附带 Babel JavaScript 编译器。查看 Babel 文档,了解其支持的转换的更多详细信息。

React Native 启用的所有转换的完整列表可以在 @react-native/babel-preset 中找到。

转换代码
ECMAScript 5
保留字
promise.catch(function() {...});
ECMAScript 2015 (ES6)
箭头函数
<C onPress={() => this.setState({pressed: true})} />
块级作用域
let greeting = 'hi';
调用展开
Math.max(...array);
class C extends React.Component {render() { return <View />; }}
计算属性名
const key = 'abc'; const obj = {[key]: 10};
常量
const answer = 42;
解构
const {isActive, style} = this.props;
for…of 循环
for (var num of [1, 2, 3]) {...};
函数名
let number = x => x;
字面量
const b = 0b11; const o = 0o7; const u = 'Hello\u{000A}\u{0009}!';
模块
import React, {Component} from 'react';
对象简洁方法
const obj = {method() { return 10; }};
对象简写符号
const name = 'vjeux'; const obj = {name};
参数
function test(x = 'hello', {a, b}, ...args) {}
剩余参数
function(type, ...args) {};
简写属性名
const o = {a, b, c};
粘性正则表达式
const a = /o+/y;
模板字面量
const who = 'world'; const str = `Hello ${who}`;
Unicode 正则表达式
const string = 'foo💩bar'; const match = string.match(/foo(.)bar/u);
ECMAScript 2016 (ES7)
幂运算符
let x = 10 ** 2;
ECMAScript 2017 (ES8)
异步函数
async function doStuffAsync() {const foo = await doOtherStuffAsync();};
函数尾逗号
function f(a, b, c,) {};
ECMAScript 2018 (ES9)
对象展开
const extended = {...obj, a: 10};
ECMAScript 2019 (ES10)
可选的 Catch Binding
try {throw 0; } catch { doSomethingWhichDoesNotCareAboutTheValueThrown();}
ECMAScript 2020 (ES11)
动态导入
const package = await import('package'); package.function()
空值合并运算符
const foo = object.foo ?? 'default';
可选链
const name = obj.user?.name;
ECMAScript 2022 (ES13)
类字段
class Bork {static a = 'foo'; static b; x = 'bar'; y;}
Stage 1 提案
导出默认值 From
export v from 'mod';
其他
Babel 模板
template(`const %%importName%% = require(%%source%%);`);
Flow
function foo(x: ?number): string {};
ESM 到 CJS
export default 42;
JSX
<View style={{color: 'red'}} />
对象赋值
Object.assign(a, b);
React Display Name
const bar = createReactClass({});
TypeScript
function foo(x: {hello: true, target: 'react native!'}): string {};

Polyfills

许多标准函数在所有支持的 JavaScript 运行时中也可用。

浏览器

ECMAScript 2015 (ES6)

ECMAScript 2016 (ES7)

ECMAScript 2017 (ES8)

特定

  • __DEV__