javascript - 如何在 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
有可能吗?
解决方案
如果你想尝试它...
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% 相信你评估的东西,不要这样做。
推荐阅读
- automation - AHK 脚本双击每 X 次左键单击(随机双击每几次单击)
- python - boto3 的 S3.Bucket.download_file 的响应语法
- python - 如何更改 Jupyter 看到的 Python 版本?
- winapi - 比较 16 bpp 和 32 bpp 位图转换
- rust - 枚举匹配:第一臂意外总是匹配
- javascript - 我如何在任何地方使用 AsyncStorage 数据?
- java - 如何使用循环语句而不是 go to 语句
- rest - 如何从 Jenkins REST API 的 POST 请求的结果中获取相应的构建?
- spring-boot - 如果令牌无效,Keycloak + Spring Boot + Spring Security 会以某种方式进行令牌验证 2 次
- flutter - 未解决的参考:firebasemessaging