反应本机和评估范围

时间:2019-12-18 15:38:58

标签: javascript react-native eval

我正在尝试使用eval在运行时创建一个react元素。是的,我知道,评估是有风险的。但是,假设有一些安全措施,并且代码来自受信任的来源,我想在运行时创建一个元素。

这就是我所拥有的。

import React from 'react';
import {Text} from 'react-native';

export default function CustomComponent(){
  const source = `
    function bar() {
      var foo = function foo() {
        return React.createElement(Text, null, "Hello");
      };

      return foo;
    }
  `;

  eval(source);
  const hello = bar();
  return hello();
}

上面的代码抱怨没有定义React。 因此,我改为这样做,并且可行。

// as before
const narrowScope = (src) => {
  const React = require('react');
  const Text = require('react-native').Text;
  eval(src);
  const hello = bar();
  return hello();
};

return narrowScope(source);

那么为什么第二个版本而不是第一个版本有效? React应该不属于第一个版本的范围吗?

谢谢

0 个答案:

没有答案