我正在尝试从 API 获取的字符串中以本机反应动态生成 UI。我不太明白为什么 eval(( 在这个例子中不起作用:
<View style={{flex:1}}>
{eval('React.createElement(Text, { style: styles.highlight }, `This is my text`)')}
</View>
错误:
引用错误:找不到变量:反应
即使我收到此错误,如果我直接运行相同的代码而不进行 eval 它就可以完美运行:
<View style={{flex:1}}>
{React.createElement(Text, { style: styles.highlight }, `This is my text`)}
</View>
没有错误,文本"这是我的文本"正确呈现。
知道为什么会这样吗?
一种解决方案可能是将 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")');
})();