首页 > 解决方案 > 如何在 eval 中使用本地范围

问题描述

我有一个使用 React 的模块 JS

 import React from 'react'

我的组件

export default class TaskDetail extends Component {...

我有一个代表代码的字符串:

str=`props => {
  return React.createElement(.....

我会在这样的模块JS中使用这段代码:

const MyCustomWidget = eval(str)

这样一个就等于写:

const MyCustomWidget = props => {
  return React.createElement(.....

我使用 MyCustomWidget 在 react-jsonschema-form 中创建自定义元素

我的问题的重点是:在我的模块中我已经导入了 React 但我有错误 React is not defined 那是因为 eval 的结果有另一个范围......如果我写在我的模块之上:

 window.React = React

有用!但我不想使用

可以使用 eval 并使用我的模块的范围吗?我想在我的模块中使用我导入的 React 变量而不使用 window.React=React

有可能吗?

标签: javascriptreactjsreact-redux

解决方案


如果你想尝试它...

const evalInContext = a =>
    // eslint-disable-next-line no-new-func
    new Function('require', 'const React = require("react");' + a).bind(
        null,
        require
    );

看看他们如何在 react-styleguidist https://github.com/styleguidist/react-styleguidist/blob/34f3c83e76/src/client/rsg-components/ReactExample/ReactExample.spec.js的实时编辑器中评估和运行反应代码

再一次,如果你不能 100% 相信你评估的东西,不要这样做。


推荐阅读