我正在尝试使用Polymer项目中的PWA Starter Kit制作一个小型应用。
是否可以在我的LitElement中使用https://material.io/develop/web/components/input-controls/text-field/中的Web组件?我要使用文本区域。
我尝试过的事情:
import {html, customElement, LitElement} from "lit-element";
//
import {MDCTextField} from '@material/textfield';
@customElement('text-editor')
export class TextEditor extends LitElement {
protected render() {
return html`<div class="mdc-text-field mdc-text-field--textarea">
<textarea id="textarea" class="mdc-text-field__input" rows="8" cols="40"></textarea>
<div class="mdc-notched-outline">
<div class="mdc-notched-outline__leading"></div>
<div class="mdc-notched-outline__notch">
<label for="textarea" class="mdc-floating-label">Textarea Label</label>
</div>
<div class="mdc-notched-outline__trailing"></div>
</div>
</div>`
}
}
但是,因为我在任何地方都没有使用“ MDCTextField”,所以TypeScript编译器会抱怨“已声明'MDCTextField',但从未读取过它的值。”
我确实在HTML中呈现了一个文本区域,但是没有应用任何样式。
如何在LitElement中重用MDCTextField Web组件?
答案 0 :(得分:3)
是的,您必须使用LitElement的static styles,它在不支持的浏览器中使用可构造样式以及后备功能:
import { html, customElement, LitElement, unsafeCSS } from 'lit-element';
import { MDCTextField } from '@material/textfield';
// IMPORTANT: USE WEBPACK RAW-LOADER OR EQUIVALENT
import style from 'raw-loader!@material/textfield/dist/mdc.textfield.css';
@customElement('text-editor')
export class TextEditor extends LitElement {
static styles = [unsafeCSS(style)];
private textField?: MDCTextField;
connectedCallback() {
super.connectedCallback();
const elm = this.shadowRoot!.querySelector('.mdc-text-field')! as HTMLElement;
if (elm && !this.textField) {
// Element is re-attached to the DOM
this.makeTextField();
}
}
disconnectedCallback() {
if (this.textField) {
this.textField.destroy();
this.textField = undefined;
}
}
render() {
return html`
<div class='mdc-text-field mdc-text-field--textarea'>
<textarea id='textarea' class='mdc-text-field__input' rows='8' cols='40'></textarea>
<div class='mdc-notched-outline'>
<div class='mdc-notched-outline__leading'></div>
<div class='mdc-notched-outline__notch'>
<label for='textarea' class='mdc-floating-label'>Textarea Label</label>
</div>
<div class='mdc-notched-outline__trailing'></div>
</div>
</div>`;
}
firstUpdated() {
// Executed just once
this.makeTextField();
}
private makeTextField() {
const elm = this.shadowRoot!.querySelector('.mdc-text-field')! as HTMLElement;
this.textField = new MDCTextField(elm);
}
}
这些是您需要做的事情:
MDCTextField
首次渲染组件时初始化firstUpdated
。MDCTextField
实例。