为什么 eval() 在 React Native 中不起作用?

Ism*_*eos 5 javascript eval react-native

我正在尝试从从 API 获取的字符串中动态生成 UI 以响应本机。我不太明白为什么 eval() 在这个例子中不起作用:

<View style={{flex:1}}>
     {eval('React.createElement(Text, { style: styles.highlight }, `This is my text`)')}

</View>
Run Code Online (Sandbox Code Playgroud)

错误:

参考错误:找不到变量:反应

即使我收到此错误,如果我在没有 eval 的情况下直接运行相同的代码,它也能完美运行:

<View style={{flex:1}}>
      {React.createElement(Text, { style: styles.highlight }, `This is my text`)}
</View>

Run Code Online (Sandbox Code Playgroud)

没有错误,文本“这是我的文本”正确呈现。

知道为什么会这样吗?

Nic*_*nos 6

解决方案可能是将 eval 执行包装在函数内并将每个变量复制到this.

转译器/压缩器/丑化器不会更改任何对象的属性名称,也不会重命名,this因为它是关键字。

所以,这样的事情应该有效

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

(function() {
  this.React = React;
  this.Text = Text;  

  eval('this.React.createElement(this.Text, {}, "This is my text")');
})();

Run Code Online (Sandbox Code Playgroud)