问题
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