“Cannot read property 'MDCSwitch' of undefined” error when importing an MDC Switch component

你离开我真会死。 提交于 2020-08-10 23:08:48

问题


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.

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);
  });

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

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

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": {}
}

Any ideas?


回答1:


Turns out the code I should have been using was:

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

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




回答2:


A bit of history on why it's different than the rest.

switch is a reserved keyword in JS, so the component name had to be modified.



来源:https://stackoverflow.com/questions/57447776/cannot-read-property-mdcswitch-of-undefined-error-when-importing-an-mdc-swit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!