为什么 eval() 不适用于导入的函数?

在 React 中,为什么 eval() 仅适用于在同一文件中定义的函数,而不适用于导入的函数?


在我的代码示例中,alertY是一个导入的函数并alertX在同一个文件中定义。当函数名称传递给 时onClick,alertX和 都alertY有效。


但是,当该函数在 eval 内部作为字符串直接调用然后传递给 时onClick,只能alertX起作用。alertY导致 ReferenceError 如下:


Uncaught ReferenceError: alertY is not defined

    at eval (eval at onClick (index.js? [sm]:13)

源代码/索引.js


import { alertY } from "./alertY";


function alertX() {

  alert("x");

}


function App() {

  return (

    <div className="App">

      <button onClick={alertX}>alertX</button>

      <button onClick={alertY}>alertY</button>


      <button onClick={() => eval(`alertX()`)}>evalX</button>

      <button onClick={() => eval(`alertY()`)}>evalY</button>

    </div>

  );

}

源代码/警报.js


export function alertY() {

  alert("y");

}

 

第二个问题:如 Mhd 的回答所示,为什么import * as alerts from "./alertY"有效而import { alertY } from "./alertY"无效?


ABOUTYOU
浏览 326回答 1
1回答

拉丁的传说

试试这个:import * as alerts from "./alertY";function alertX() {&nbsp; alert("x");}function App() {&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <button onClick={alertX}>alertX</button>&nbsp; &nbsp; &nbsp; <button onClick={alerts.alertY}>alertY</button>&nbsp; &nbsp; &nbsp; <button onClick={() => eval(`alertX()`)}>evalX</button>&nbsp; &nbsp; &nbsp; <button onClick={() => eval(`alerts.alertY()`)}>evalY</button>&nbsp; &nbsp; </div>&nbsp; );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript