“无法读取未定义的属性'MDCSwitch'";导入MDC开关组件时出现错误 [英] "Cannot read property 'MDCSwitch' of undefined" error when importing an MDC Switch component

查看:82
本文介绍了“无法读取未定义的属性'MDCSwitch'";导入MDC开关组件时出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用express和material-components-web编写Node应用程序,但遇到TextField有效但Switch无法正常工作的问题.

I'm writing a Node app using express and material-components-web and I'm having a problem where TextField works but Switch does not.

这是我用来将相关JS附加到元素上的代码:

Here's the code I'm using to attach the relevant JS to the elements:

  [].slice.call(document.querySelectorAll('.mdc-text-field')).forEach(
  function(ele) {
    mdc.textField.MDCTextField.attachTo(ele);
  });

  [].slice.call(document.querySelectorAll('.mdc-switch')).forEach(
  function(ele) {
    mdc.switch.MDCSwitch.attachTo(ele);
  });

当我注释掉文本字段的代码时,它停止工作,因此 mdc.textField.MDCTextField 部分肯定可以工作.

When I comment out the code for the textfield it stops working, so the mdc.textField.MDCTextField part is definitely working.

我在Chrome开发工具中遇到的错误是:

The error I get in Chrome Dev Tools is:

(index):446 Uncaught TypeError: Cannot read property 'MDCSwitch' of undefined
    at (index):446
    at Array.forEach (<anonymous>)
    at (index):444

我的 package.json 文件如下所示:

My package.json file looks like this:

{
  "name": "emergencyregister",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {    
    "debug": "~2.6.9",
    "ejs": "^2.6.2",
    "eslint": "^5.7.0",
    "express": "^4.16.4",
    "helmet": "^3.20.0",
    "http-errors": "~1.6.2",
    "material-components-web": "^3.1.0",
    "mysql": "^2.16.0",
    "node-sass": "^4.12.0",
    "node-sass-middleware": "^0.11.0",
    "serve-favicon": "^2.5.0"
  },
  "devDependencies": {}
}

有什么想法吗?

推荐答案

原来我应该使用的代码是:

Turns out the code I should have been using was:

  [].slice.call(document.querySelectorAll('.mdc-switch')).forEach(
  function(ele) {
    mdc.switchControl.MDCSwitch.attachTo(ele);
  });

要解决这个问题,我将mdc对象打印到控制台以查找所有不同的项目:

To work this out I printed the mdc object to the console to find all of the different items:

这篇关于“无法读取未定义的属性'MDCSwitch'";导入MDC开关组件时出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆