为什么eval()在React Native中不起作用? [英] Why eval() is not working in React Native?
问题描述
我正在尝试通过从API提取的String进行本机反应来动态生成UI.我不太明白为什么eval()在此示例中不起作用:
I'm trying to generate UI dynamically in react native from a String fetched from an API. I don't quite get why eval() is not working in this example:
<View style={{flex:1}}>
{eval('React.createElement(Text, { style: styles.highlight }, `This is my text`)')}
</View>
错误:
ReferenceError:找不到变量:React
ReferenceError: can't find variable: React
即使我遇到此错误,但如果我直接运行相同的代码而没有eval,它也可以正常运行:
Even though I'm getting this error, if I run the same code directly without eval it works perfectly:
<View style={{flex:1}}>
{React.createElement(Text, { style: styles.highlight }, `This is my text`)}
</View>
没有错误,并且正确显示了这是我的文字"文本.
No error and the text "This is my text" is rendered properly.
知道为什么会这样吗?
推荐答案
一种解决方案是将eval执行包装在一个函数中,然后将每个变量复制到 this
中.
A solution could be to wrap the eval execution inside a function and copy each variable into this
.
transpiler/minifier/uglifier不会更改任何对象的属性名称,也不会重命名 this
,因为它是关键字.
The transpiler/minifier/uglifier won't change the names of the properties of any object, and also won't rename this
because it's a keyword.
所以,这样的事情应该起作用
So, something like this should work
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")');
})();
这篇关于为什么eval()在React Native中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!