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

标签 javascript react-native eval

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

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

</View>

错误:

ReferenceError: can't find variable: React



即使我收到此错误,如果我在没有 eval 的情况下直接运行相同的代码,它也可以完美运行:
<View style={{flex:1}}>
      {React.createElement(Text, { style: styles.highlight }, `This is my text`)}
</View>


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

知道为什么会这样吗?

最佳答案

一个解决方案可能是将 eval 执行包装在一个函数中并将每个变量复制到 this .
transpiler/minifier/uglifier 不会改变任何对象的属性名称,也不会重命名 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")');
})();

关于javascript - 为什么 eval() 在 React Native 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57759924/

相关文章:

r - 评估包含另一个调用的调用(调用中的调用)

javascript - 为什么 ES6 WeakMap 不可枚举?

javascript - 加载异步JS然后调用函数?

javascript - navigator.serviceWorker 当注册多个 service worker 时

javascript - 为什么我的箭头函数有原型(prototype)属性?

shell - 使用 `eval` 用文件中的文本定义函数是邪恶的吗?

javascript - 相机 react native 时出现错误 "null is not an object"

react-native - 如何使用 tcomb-form-native 切换到下一个输入字段?

ios - 代码推送 : How to deploy to multiple build versions of the same deployment config?

scala - 将变量强制转换为 Scala 中的方法 "Runtime Evaluation"