サルでもわかるWEBプログラミング

フリーソフトのみでホームページ作成

ユーザ用ツール

サイト用ツール


サイドバー

目次

サルでもわかる機械学習

このページへのアクセス
今日: 1 / 昨日: 0
総計: 2

sidebar

00.stencil:03.stencilの_propと_state


03.Stencilの@propと@state

Angularには、双方向データバインディングがあるのですが、Stencilには単方向データバインディングしかないです。

そのため、Stencilでは、フォームからの入力データを@state()で受け取り、何かに入れて、render()で表示するようにプログラミングする必要があります。

引用元:https://www.joshmorony.com/building-a-pwa-with-stencil-storage-and-services/

  componentDidLoad() {
    const router = document.querySelector("ion-router");
 
    // Refresh data every time view is entered
    router.addEventListener("ionRouteDidChange", async () => {
      const holdings = await Holdings.getHoldings();
      this.holdings = [...holdings];
    });
  }

@prop()の解説のリンク

https://stenciljs.com/docs/properties
Prop Decorator(公式ドキュメント)

Props should be used to pass data down from the parent component to the child component.

親コンポーネント内のデータを、子コンポーネントに伝達するためには、親コンポーネント内でデータに@prop()というデコレータをつけて、エクスポートして、それを子コンポーネントで受けとるという作業が必要になります。

公式ドキュメントには以下のように記載させています。後で実際に試してみたいと思います。

親コンポーネント

import { Prop } from '@stencil/core';
 
...
export class TodoList {
  @Prop() color: string;
  @Prop() favoriteNumber: number;
  @Prop() isSelected: boolean;
  @Prop() myHttpService: MyHttpService;
}

子コンポーネントで、上記のcolorを受けとる方法

logColor() {
  console.log(this.color)
}

@state()の解説のリンク

https://stenciljs.com/docs/state
State Decorator(公式ドキュメント)

内容が変化する可能性のあるデータには、
@state()デコレータをつけるそうです。

Any changes to a @State() property will cause the components render function to be called again.
@State() propertyが変更されるたびに、コンポーネントのrender関数が呼び出される(再描画される)。

https://www.joshmorony.com/building-a-pwa-with-stencil-storage-and-services/ では、

コンポーネント src/components/app-home/app-home.tsx で、

  @State() holdings: Holding[] = [];

と、holdingsに@State()をつけることで、

  componentDidLoad() {
    const router = document.querySelector("ion-router");

    // Refresh data every time view is entered
    router.addEventListener("ionRouteDidChange", async () => {
      const holdings = await Holdings.getHoldings();
      this.holdings = [...holdings];
    });
  }

により、ページのアドレスが変化するたびに、holdingsが再描画されて、表示されるものが最新のものになるようにしています。

リンク


00.stencil/03.stencilの_propと_state.txt · 最終更新: 2019/09/26 by adash333