HTML 属性への JavaScript プロパティの反映

公開 JavaScript プロパティを、表示される Lightning Web コンポーネントの HTML で属性として表示するかどうかを制御できます。スクリーンリーダーや他の支援技術は HTML 属性を使用するため、アクセス性の高いコンポーネントを作成する場合はプロパティを属性として表示することが重要です。

すべての HTML 属性は、デフォルトではリアクティブです。コンポーネント HTML で属性値が変更されると、コンポーネントが再表示されます。

属性を公開プロパティとして公開することで属性を制御する場合、デフォルトでは属性は HTML 出力に表示されなくなります。表示される HTML に値を属性として渡す (プロパティを反映するため) には、プロパティの getter と setter を定義して setAttribute() メソッドをコールします。

setter 内で操作を実行することもできます。項目を使用して、計算された値を保持します。

次の例では、title を公開プロパティとして表示しています。タイトルを大文字に変換してから、_privateTitle プロパティを使用してタイトルの計算値を保持します。setter は、setAttribute() をコールしてプロパティの値を HTML 属性に反映します。

1// myComponent.js
2import { LightningElement, api } from "lwc";
3
4export default class MyComponent extends LightningElement {
5  _privateTitle;
6
7  @api
8  get title() {
9    return this._privateTitle;
10  }
11
12  set title(value) {
13    this._privateTitle = value.toUpperCase();
14    this.setAttribute("title", this._privateTitle);
15  }
16}
1/* parent.html */
2<template>
3  <c-my-component title="Hover Over the Component to See Me"></c-my-component>
4</template>
1/* Generated HTML */
2<c-my-component title="HOVER OVER THE COMPONENT TO SEE ME">
3  <div>Reflecting Attributes Example</div>
4</c-my-component>

JavaScript プロパティが HTML 属性にどのように反映されるかをしっかりと理解するため、同じコードで setAttribute() をコールしない場合を見てみましょう。生成される HTML には title 属性が含まれていません。

1// myComponent.js
2import { LightningElement, api } from "lwc";
3
4export default class MyComponent extends LightningElement {
5  _privateTitle;
6
7  @api
8  get title() {
9    return this._privateTitle;
10  }
11
12  set title(value) {
13    this._privateTitle = value.toUpperCase();
14    // this.setAttribute('title', this._privateTitle);
15  }
16}
1/* parent.html */
2<template>
3  <c-my-component title="Hover Over the Component to See Me"></c-my-component>
4</template>
1/* Generated HTML */
2<c-my-component>
3  <div>Reflecting Attributes Example</div>
4</c-my-component>

値を設定する前に、すでにコンシューマによって設定されているかどうかを確認します。

1// myComponent.js
2import { LightningElement } from "lwc";
3
4export default class MyComponent extends LightningElement {
5  connectedCallback() {
6    const tabindex = this.getAttribute("tabindex");
7
8    // Set the tabindex to 0 if it hasn’t been set by the consumer.
9    if (!tabindex) {
10      this.setAttribute("tabindex", "0");
11    }
12  }
13}

this.setAttribute() を使用して tabindex を設定すると、次のマークアップが生成されます。

1<c-my-component tabindex="0"></c-my-component>

これらの属性を設定するには、setAttribute() を使用します。

  • for
  • aria-activedescendant
  • aria-controls
  • aria-describedby
  • aria-details
  • aria-errormessage
  • aria-flowto
  • aria-labelledby
  • aria-owns

表示される HTML で HTML 属性を非表示にするには、removeAttribute() をコールします。

関連トピック

The Japanese Summer '24 guide is now live

日本語の Summer '24 ガイドが公開されました! 「Component Reference (コンポーネントリファレンス)」は、以前と同様にコンポーネントライブラリにあります。