Why eval() is not working in React Native?

♀尐吖头ヾ 提交于 2021-02-08 15:10:59

问题


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>

Error:

ReferenceError: can't find variable: React

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.

Any idea why this is happening?


回答1:


A solution could be to wrap the eval execution inside a function and copy each variable into 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")');
})();



来源:https://stackoverflow.com/questions/57759924/why-eval-is-not-working-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!