5

我有这个代码

    this.mdc_text = mdc.textField.MDCTextField.attachTo(this.$el);
    if (this.autofocus) {
        this.mdc_text.activateFocus();
    }

但是函数 activateFocus 是未定义的。我怎样才能集中注意力?

https://material.io/develop/web/components/input-controls/text-field/

谢谢

4

1 回答 1

4

activateFocusMDCTextFieldFoundation在为框架创建组件时使用 with 。在您的情况下,您似乎正在尝试以编程方式聚焦 MDC 文本字段,因此请改用该focus方法。

const field = mdc.textField.MDCTextField.attachTo(document.querySelector('.mdc-text-field'));
field.focus();
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Material TextField</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700">
    <link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet">
    <script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>   
  </head>
  <body>  
    <label class="mdc-text-field mdc-text-field--filled">
      <span class="mdc-text-field__ripple"></span>
      <input class="mdc-text-field__input" type="text">
      <span class="mdc-floating-label">Hint text</span>
      <span class="mdc-line-ripple"></span>
    </label> 
  </body>
</html>

顺便说一句,如果您希望 TextField 自动关注页面加载,那么您可以将该autofocus属性添加到inputhtml 中的元素。

于 2018-10-29T22:39:31.980 回答