我正在尝试从从 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/