【发布时间】:2020-06-03 04:19:44
【问题描述】:
目前正在学习“什么是闭包”并尝试此练习代码。在 Visual Studio 代码中运行。
for (let [idx,btn] of buttons.entries()) {
btn.addEventListener(
"click",
function onClick(){
console.log(
`Clicked on button (${ idx })!
`);
}
);
}
预计每次迭代都会获得新的块范围 (idx,btn) 变量;并且期望循环每次都会创建一个新的内部 onClick(..) 函数。但是它得到了这个错误。
PS C:\Users\leePC\babel\public\src> node test.js
C:\Users\leePC\babel\public\src\test.js:1
for (let [idx,btn] of buttons.entries()) {
btn.addEventListener("click",function onClick(){
console.log(`Clicked on button (${ idx })!`); }); }
^
ReferenceError: buttons is not defined
at Object.<anonymous>
(C:\Users\leePC\babel\public\src\test.js:1:31)
at Module._compile
(internal/modules/cjs/loader.js:1157:30)
at Object.Module._extensions..js
(internal/modules/cjs/loader.js:1177:10)
at Module.load (internal/modules/cjs/loader.js:1001:32)
at Function.Module._load
(internal/modules/cjs/loader.js:900:14)
at Function.executeUserEntryPoint [as runMain]
(internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
既然有人说我应该实现
npm install react-uikit-button --save;
// ES6
import Button from 'react-uikit-button';
// ES5
var Button = require('react-uikit-button');
并尝试在代码前面导入,但还是不行。它弹出不同的错误... 如何解决这个问题?
编辑:当我使用 import 语句然后通过 Babel 转换此代码时,发生此错误。(在 Visual Studio 代码中)
'Button' is declared but its value is never read
【问题讨论】:
-
never read表示您尚未在代码中的任何位置使用 Button -
ReferenceError: buttons is not defined 那么,你在哪里定义了
buttons? (听起来你没有) -
哦,我很愚蠢..谢谢
标签: javascript node.js reactjs ecmascript-6