Properties
Propsとは、HTML要素上で公開されるカスタム属性/プロパティのことです。これらを使うことで、開発者はコンポーネントにデータを渡し、そのデータを表示したり、 他の目的で利用したりすることができます。
The Prop Decorator (@Prop())
コンポーネントの props は、次のように Stencil の @Prop() デコレーターで宣言します。
// First, we import Prop from '@stencil/core'
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'todo-list',
})
export class TodoList {
// Second, we decorate a class member with @Prop()
@Prop() name: string;
render() {
// Within the component's class, its props are
// accessed via `this`. This allows us to render
// the value passed to `todo-list`
return <div>To-Do List Name: {this.name}</div>
}
}
上の例では、@Prop()がnameクラスのメンバー、つまりstringの前に配置されています。
@Prop()とnameを加えることで、Stencilはnameを要素の属性として表現することができます。そして、この属性は、コンポーネントが使用される場所でどこにでも設定することがで
きます。
{/* Here we use the component in a TSX file */}
<todo-list name={"Tuesday's To-Do List"}></todo-list>
<!-- Here we use the component in an HTML file -->
<todo-list name="Tuesday's To-Do List"></todo-list>
上の例では、todo-listコンポーネントがTSXやHTMLでもほぼ同じように使用されています。二つのコンポーネントの唯一の違いは、
TSXでは、propに割り当てられた値(この場合はname)がカッコで囲まれている点です。しかし、場合によっては、
propsがコンポーネントに渡される方法がHTMLとTSXで少し異なることがあります。
変数名の大文字と小文字
JavaScriptエコシステムでは、変数の名前を「camelCase」と付けるのが一般的です。以下のコンポーネントの例を見てみましょう。
クラスメンバー、thingToDoは、実際には camelCasedです。
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
// thingToDo is 'camelCased'
@Prop() thingToDo: string;
render() {
return <div>{this.thingToDo}</div>;
}
}
thingToDoはpropなので、todo-list-itemコンポーネントを使用すると、その値を提供することができます。
thingToDoのようなcamelCasedやpropに値を与えることは、TSXやHTMLにおいてもほぼ同じです。
TSXファイル内でコンポーネントを使用する場合、ある属性は camelCaseを使用します。
<todo-list-item thingToDo={"Learn about Stencil Props"}></todo-list-item>
HTMLでは、属性は「ダッシュケース」形式で記述する必要があります。具体的には、次のようになります。
<todo-list-item thing-to-do="Learn about Stencil Props"></todo-list-item>
データの流れ
props は親コンポーネントから子コンポーネントにデータを渡すために使います。
以下の例では、todo-listコンポーネントが、3つの todo-list-itemコンポーネントを使用して、ToDoリストを表示する方法を示しています。
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'todo-list',
})
export class TodoList {
render() {
return (
<div>
<h1>To-Do List Name: Stencil To Do List</h1>
<ul>
{/* Below are three Stencil components that are children of `todo-list`, each representing an item on our list */}
<todo-list-item thingToDo={"Learn about Stencil Props"}></todo-list-item>
<todo-list-item thingToDo={"Write some Stencil Code with Props"}></todo-list-item>
<todo-list-item thingToDo={"Dance Party"}></todo-list-item>
</ul>
</div>
)
}
}
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
@Prop() thingToDo: string;
render() {
return <li>{this.thingToDo}</li>;
}
}
子コンポーネントは、親コンポーネントの存在や情報を知ったり、参照したりしてはいけません。これにより、Stencilが正常に機能することが保証されます。 コンポーネントを効率的に再レンダリングすることができます。コンポーネントの参照をプロパティとして渡すと、意図しない副作用が発生する可能性があります。
変更可能性
プロパティは、コンポーネントのロジック内ではデフォルトで変更不可能です。ユーザーによって値が設定された後、 コンポーネントはその値を内部で変更することはできません。propの可変性をより細かく制御したい場合は、 このドキュメントの変更可能なオプションのセクションを参照してください。
Types
プロップには、boolean、number、string、あるいはObjectやArrayといったものが含まれます。以下の例では、
todo-list-itemを拡張し、さらにいくつかの異なるタイプのpropsを追加しています。
import { Component, Prop, h } from '@stencil/core';
// `MyHttpService` is an `Object` in this example
import { MyHttpService } from '../some/local/directory/MyHttpService';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
@Prop() isComplete: boolean;
@Prop() timesCompletedInPast: number;
@Prop() thingToDo: string;
@Prop() myHttpService: MyHttpService;
}
真偽値型の props
Stencilコンポーネント上で、型が booleanであるプロパティは、次のように宣言できます:
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
@Prop() isComplete: boolean;
}
HTMLでこのバージョンの todo-list-itemを使用するには、文字列“"true"/"false"”をそのコンポーネントに渡します。
<!-- Set isComplete to 'true' -->
<todo-list-item is-complete="true"></todo-list-item>
<!-- Set isComplete to 'false' -->
<todo-list-item is-complete="false"></todo-list-item>
TSXでこのバージョンの todo-list-itemを使用する場合、true/falseが使用され、それらはカッコで囲まれて表されます。
// Set isComplete to 'true'
<todo-list-item isComplete={true}></todo-list-item>
// Set isComplete to 'false'
<todo-list-item isComplete={false}></todo-list-item>
Stencilが、boolean型のプロップを扱う際に、いくつか注意すべき点があります。
- ブールプロパティの値が
falseになるのは、HTMLに文字列"false"が指定されている場合です。
<!-- The 'todo-list-item' component will have an isComplete value of `false` -->
<todo-list-item is-complete="false"></todo-list-item>
- ブールプロパティの値が HTML内で
"false"ではない文字列が指定されている場合、その値はtrueになります。
<!-- The 'todo-list-item' component will have an isComplete value of -->
<!-- `true` for each of the following examples -->
<todo-list-item is-complete=""></todo-list-item>
<todo-list-item is-complete="0"></todo-list-item>
<todo-list-item is-complete="False"></todo-list-item>
- boolean propの価値は、デフォルト値がない場合、または以下のいずれかの条件が当てはまる場合、
undefinedに なります。- このコンポーネントを使用する場合、そのプロップは含まれていません。
- このコンポーネントを使用する際には、そのプロップが含まれますが、値は与えられていません。
<!-- Both examples using the 'todo-list-item' component will have an -->
<!-- isComplete value of `undefined` -->
<todo-list-item></todo-list-item>
<todo-list-item is-complete></todo-list-item>
数値型の props
Stencilコンポーネント上で、型が numberであるプロパティは、次のように宣言できます:
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
@Prop() timesCompletedInPast: number;
}
HTMLでこのバージョンの todo-list-itemを使用するには、数値を文字列としてコンポーネントに渡します。
<!-- Set timesCompletedInPast to '0' -->
<todo-list-item times-completed-in-past="0"></todo-list-item>
<!-- Set timesCompletedInPast to '23' -->
<todo-list-item times-completed-in-past="23"></todo-list-item>
TSXでこのバージョンの todo-list-itemを使用するには、中括弧で囲まれた数値をコンポーネントに渡す必要があります。
// Set timesCompletedInPast to '0'
<todo-list-item timesCompletedInPast={0}></todo-list-item>
// Set timesCompletedInPast to '23'
<todo-list-item timesCompletedInPast={23}></todo-list-item>
文字列型の props
Stencilコンポーネント上で、型が stringであるプロパティは、次のように宣言できます:
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
@Prop() thingToDo: string;
}
HTMLでこのバージョンの todo-list-itemを使用するには、値を文字列としてコンポーネントに渡します。
<!-- Set thingToDo to 'Learn about Stencil Props' -->
<todo-list-item thing-to-do="Learn about Stencil Props"></todo-list-item>
<!-- Set thingToDo to 'Write some Stencil Code with Props' -->
<todo-list-item thing-to-do="Write some Stencil Code with Props"></todo-list-item>
TSXでこのバージョンのtodo-list-itemを使用するには、値をstringとしてコンポーネントに渡します。
TSXでstringの値をpropsに渡す際には、中括弧は必要ありませんが、使用することも可能です。
// Set thingToDo to 'Learn about Stencil Props'
<todo-list-item thingToDo="Learn about Stencil Props"></todo-list-item>
// Set thingToDo to 'Write some Stencil Code with Props'
<todo-list-item thingToDo="Write some Stencil Code with Props"></todo-list-item>
// Set thingToDo to 'Write some Stencil Code with Props' with curly braces
<todo-list-item thingToDo={"Learn about Stencil Props"}></todo-list-item>
オブジェクト型の props
Stencilコンポーネント上で、型が Objectであるプロパティは、次のように宣言できます:
// TodoListItem.tsx
import { Component, Prop, h } from '@stencil/core';
import { MyHttpService } from '../path/to/MyHttpService';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
// Use `@Prop()` to declare the `httpService` class member
@Prop() httpService: MyHttpService;
}
// MyHttpService.ts
export class MyHttpService {
// This implementation intentionally left blank
}
TypeScriptでは、MyHttpServiceは Objectであり、同時に「タイプ」でもあります。MyHttpServiceのようなユーザー定義のタイプを使用する場合は、
タイプは、宣言されている場所で、常に exportキーワードを使ってエクスポートされる必要があります。これを行う理由は、Stencilが必要だからです。
MyHttpServiceのインスタンスを親から TodoListItemに渡す際に、その httpServiceの種類が何であるかを知っている必要があります。
コンポーネント。
httpServiceを TSXに設定するには、カスタム要素のタグ内のプロパティ名に、希望の値を指定します。具体的には、次のようにします:
// TodoList.tsx
import { Component, h } from '@stencil/core';
import { MyHttpService } from '../MyHttpService';
@Component({
tag: 'todo-list',
styleUrl: 'todo-list.css',
shadow: true,
})
export class ToDoList {
private httpService = new MyHttpService();
render() {
return <todo-list-item httpService={this.httpService}></todo-list-item>;
}
}
注意しておくべき点は、プロパティ名が camelCaseを使用しており、その値は中括弧で囲まれているということです。
HTML属性を使って、Objectのプロパティを設定することはできません。
<!-- this will not work -->
<todo-list-item http-service="{ /* implementation omitted */ }"></todo-list-item>
その理由は、Stencilは、HTMLで記述されたオブジェクト型の文字列を JavaScriptのオブジェクトとしてシリアル化しようとしないからです。 同様に、Stencilでは、JSONからのオブジェクトのデシリシャル化には対応していません。 どちらを選んでも、実行時にコストがかかる可能性があります。また、他のネストされた JavaScriptオブジェクトへの参照を失うリスクもあります。
代わりに、プロジェクトの HTML内で、<script>タグを通じてプロパティを設定することができます。
<script>
document.querySelector('todo-list-item').httpService = { /* implementation omitted */ };
</script>
配列型の props
Stencilコンポーネント上の、Arrayであるプロパティは、次のように宣言できます:
// TodoList.tsx
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
@Prop() itemLabels: string[];
}
itemLabelsを TSXに設定するには、カスタム要素のタグ内で、そのプロパティ名を適切な値に設定します。具体的には、次のようにします:
// TodoList.tsx
import { Component, h } from '@stencil/core';
import { MyHttpService } from '../MyHttpService';
@Component({
tag: 'todo-list',
styleUrl: 'todo-list.css',
shadow: true,
})
export class ToDoList {
private labels = ['non-urgent', 'weekend-only'];
render() {
return <todo-list-item itemLabels={this.labels}></todo-list-item>;
}
}
注意しておくべき点は、プロパティ名が camelCaseを使用しており、その値は中括弧で囲まれているということです。
HTML属性を使って、Arrayのプロパティを設定することはできません。
<!-- this will not work -->
<todo-list-item item-labels="['non-urgent', 'weekend-only']"></todo-list-item>
その理由は、Stencilは、HTMLで記述された配列型の文字列を JavaScriptオブジェクトとしてシリアル化しようとしないからです。 このような処理を行うと、実行時にコストがかかります。また、他のネストされた JavaScriptオブジェクトへの参照を失うリスクもあります。
代わりに、プロジェクトの HTML内で、<script>タグを通じてプロパティを設定することができます。
<script>
document.querySelector('todo-list-item').itemLabels = ['non-urgent', 'weekend-only'];
</script>
高度な prop の型
any Type
TypeScriptのany型は、特定の値の型チェックを防ぐために使用される特殊なタイプです。なぜか、
anyはTypeScriptにおいて有効な型であるため、Stencilや
propsにもanyという型を与えることができます。以下の例は、propsを
型anyと共に使用する3つの方法を示しています。
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
// isComplete has an explicit type annotation
// of `any`, and no default value
@Prop() isComplete: any;
// label has an explicit type annotation of
// `any` with a default value of 'urgent',
// which is a string
@Prop() label: any = 'urgent';
// thingToDo has no type and no default value,
// and will be considered to be type `any` by
// TypeScript
@Prop() thingToDo;
render() {
return (
<ul>
<li>isComplete has a value of - {this.isComplete} - and a typeof value of "{typeof this.isComplete}"</li>
<li>label has a value of - {this.label} - and a typeof value of "{typeof this.label}"</li>
<li>thingToDo has a value of - {this.thingToDo} - and a typeof value of "{typeof this.thingToDo}"</li>
</ul>
);
}
}
Stencilやpropをanyとして扱う場合、propに与えられる値は、そのままの型情報を保持します。
したがって、StencilやTypeScriptは、propの型を変更しようとはしません。例を示すために、
2回ずつtodo-list-itemを使用し、それぞれ異なるpropの値を与えます。
{/* Using todo-list-item in TSX using differnt values each time */}
<todo-list-item isComplete={42} label={null} thingToDo={"Learn about any-typed props"}></todo-list-item>
<todo-list-item isComplete={"42"} label={1} thingToDo={"Learn about any-typed props"}></todo-list-item>
上記の使用例から、次のように訳されます。
- isComplete has a value of - 42 - and a typeof value of "number"
- label has a value of - - and a typeof value of "object"
- thingToDo has a value of - Learn about any-typed props - and a typeof value of "string"
- isComplete has a value of - 42 - and a typeof value of "string"
- label has a value of - 1 - and a typeof value of "number"
- thingToDo has a value of - Learn about any-typed props - and a typeof value of "string"
todo-list-itemが初めて使用された際、isCompleteには42という数値が与えられました。一方、2回目の使用時には…
「42」という文字列が受け取られます。isComplete上の型は、その値が持つ型を反映しています。つまり、「number」という型です。
「string」、それぞれです。
labelを見ると、そのプロップには default valueという記述があるにもかかわらず、実際にはそうではないことがわかります。
labelの型を「文字列」型に限定しないようにしています。todo-list-itemが初めて使用される際には、labelにも同様の処理が施されています。
nullの値は、第二の使用法では1という数値の値を受け取ります。labelに保存されている値の種類は、以下の通りです。
それぞれ、「object」と「number」として正しく報告されています。
Optional Types
TypeScriptでは、メンバーの名前の末尾に?を付けることで、そのメンバーを選択可能なものにすることができます。以下の例は、
各コンポーネントのpropsを選択可能にする方法を示しています。
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
// completeMsg is optional, has an explicit type
// annotation of `string`, and no default value
@Prop() completeMsg?: string;
// label is optional, has no explicit type
// annotation, but does have a default value
// of 'urgent'
@Prop() label? = 'urgent';
// thingToDo has no type annotation and no
// default value
@Prop() thingToDo?;
render() {
return (
<ul>
<li>completeMsg has a value of - {this.completeMsg} - and a typeof value of "{typeof this.completeMsg}"</li>
<li>label has a value of - {this.label} - and a typeof value of "{typeof this.label}"</li>
<li>thingToDo has a value of - {this.thingToDo} - and a typeof value of "{typeof this.thingToDo}"</li>
</ul>
);
}
}
Stencilまたはpropが「オプション」としてマークされている場合、Stencilは、明示的にタイプが指定されていない場合には、propの タイプを推測しようとします。上記の例では、Stencilがそれを理解できているのです。
completeMsgは文字列型です。なぜなら、明示的な型アノテーションがあるからです。labelは文字列型の値を持っているため、default valueもまた文字列型の値を持っているのです。thingToDoは明示的な型指定やデフォルト値もないため、any型になっている。
Stencilは labelの型を推測することができるため、以下のコードは型不一致のためにコンパイルできません。
{/* This fails to compile with the error "Type 'number' is not assignable to type 'string'" for the label prop. */}
<todo-list-item completeMsg={"true"} label={42} thingToDo={"Learn about any-typed props"}></todo-list-item>
注目すべき点は、HTMLファイル内でコンポーネントを使用する場合、このような型チェックは行われないということです。これは、 HTMLの制約であり、属性に与えられるすべての値はstring型である必要があります。
<!-- using todo-list-item in HTML -->
<todo-list-item complete-msg="42" label="null" thing-to-do="Learn about any-typed props"></todo-list-item>
renders:
- completeMsg has a value of - 42 - and a typeof value of "string"
- label has a value of - null - and a typeof value of "string"
- thingToDo has a value of - Learn about any-typed props - and a typeof value of "string"
Union Types
Stencilでは、プロップの種類を union typesにすることができます。
これにより、開発者として、2つ以上の既存の型を組み合わせて、新しい型を作成することができます。以下の例がその例です。
todo-list-itemは、文字列でもブール値でもある isCompleteのプロパティを受け入れることができます。
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
@Prop() isComplete: string | boolean;
}
このコンポーネントは、HTMLの両方で使用できます。
<todo-list-item is-complete="true"></todo-list-item>
<todo-list-item is-complete="false"></todo-list-item>
<todo-list-item is-complete></todo-list-item>
<todo-list-item></todo-list-item>
and TSX:
<todo-list-item isComplete={true}></todo-list-item>
<todo-list-item isComplete={false}></todo-list-item>
ユニオン型を使用する場合、コンポーネントの @Prop()値の型は、実行時に曖昧になり得ます。
提供された例において、どのような状況で @Prop() isCompleteは stringとして機能し、また、どのような時で booleanとして機能するのでしょうか?
HTMLでコンポーネントを使用する場合、属性が設定されている場合、@Prop()の実行時値は文字列となります。
これは、カスタム要素に HTML属性を設定した結果です。
<!-- Since this is HTML, the value of `isComplete` in `ToDoListItem` will be a string -->
<!-- Set isComplete to "true". -->
<todo-list-item is-complete="true"></todo-list-item>
<!-- Set isComplete to "false" -->
<todo-list-item is-complete="false"></todo-list-item>
<!-- Set isComplete to "" -->
<todo-list-item is-complete></todo-list-item>
しかし、ある属性が指定されていない場合、そのプロパティの実行時値は undefinedになります。
<!-- Since `is-complete` is omitted, the value of `isComplete` in `ToDoListItem` will be `undefined` -->
<todo-list-item></todo-list-item>
コンポーネントの属性が setAttributeを使用して設定されている場合、@Prop()の実行時値は常に coerced to a stringになります。
<script>
// both of these `setAttribute` calls set the property `isComplete` to "true" (string)
document.querySelector('todo-list-item').setAttribute('is-complete', true);
document.querySelector('todo-list-item').setAttribute('is-complete', "true");
// both of these `setAttribute` calls set the property `isComplete` to "false" (string)
document.querySelector('todo-list-item').setAttribute('is-complete', false);
document.querySelector('todo-list-item').setAttribute('is-complete', "false");
</script>
しかし、カスタム要素のプロパティが直接変更される場合、その要素の型は、提供された値に一致します。
<script>
// Set the property `isComplete` to `true` (boolean)
document.querySelector('todo-list-item').isComplete = true;
// Set the property `isComplete` to "true" (string)
document.querySelector('todo-list-item').isComplete = "true";
// Set the property `isComplete` to `false` (boolean)
document.querySelector('todo-list-item').isComplete = false;
// Set the property `isComplete` to "false" (string)
document.querySelector('todo-list-item').isComplete = "false";
</script>
TSXでコンポーネントを使用する場合、@Prop()の型は、提供された値に一致します。
// Since this is TSX, the value of `isComplete` in `ToDoListItem`
// depends on the type of the value passed to the component.
//
// Set the property `isComplete` to `true` (boolean)
<todo-list-item isComplete={true}></todo-list-item>
// Set the property `isComplete` to "true" (string)
<todo-list-item isComplete={"true"}></todo-list-item>
// Set the property `isComplete` to `false` (boolean)
<todo-list-item isComplete={false}></todo-list-item>
// Set the property `isComplete` to "false" (string)
<todo-list-item isComplete={"false"}></todo-list-item>
Default Values
Stencilプロパティについては、プロパティが指定されない場合の代替値として、デフォルト値を設定することができます。
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'component-with-some-props',
})
export class ComponentWithSomeProps {
@Prop() aNumber = 42;
@Prop() aString = 'defaultValue';
render() {
return <div>The number is {this.aNumber} and the string is {this.aString}</div>
}
}
HTMLでも TSXでも、このコンポーネントを使用しても、「その数は42であり、文字列は defaultValueである」という表示になります。 コンポーネントに値が渡されない場合:
<component-with-some-props></component-with-some-props>
コンポーネントのデフォルト値は、propに値を指定することで変更できます。
以下の例では、「数字は7であり、文字列は defaultValueです」と表示されます。aNumberに指定された値の仕方に注目してください。
デフォルト値を上書きしますが、aStringのデフォルト値は変わりません。
<component-with-some-props a-number="7"></component-with-some-props>
Inferring Types from Default Values
デフォルト値が指定されている場合、Stencilはそのデフォルト値から、そのプロパティの種類を推測することができます。
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'component-with-many-props',
})
export class ComponentWithManyProps {
// both props below are of type 'boolean'
@Prop() boolean1: boolean;
@Prop() boolean2 = true;
// both props below are of type 'number'
@Prop() number1: number;
@Prop() number2 = 42;
// both props below are of type 'string'
@Prop() string1: string;
@Prop() string2 = 'defaultValue';
}
必須プロパティ
prop 名の後ろに ! を付けると、Stencil はその属性またはプロパティを必須として扱います。これにより、
このコンポーネントは、TSXで使用されています。その特性は、以下のように利用されています。
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
// Note the '!' after the variable name.
@Prop() thingToDo!: string;
}
prop の検証
Propの有効性を確認するために、@Watch()デコレータを使用することができます。
import { Component, Prop, Watch, h } from '@stencil/core';
@Component({
tag: 'todo-list-item',
})
export class TodoList {
// Mark the prop as required, to make sure it is provided when we use `todo-list-item`.
// We want stricter guarantees around the contents of the string, so we'll use `@Watch` to perform additional validation.
@Prop() thingToDo!: string;
@Watch('thingToDo')
validateName(newValue: string, _oldValue: string) {
// don't allow `thingToDo` to be the empty string
const isBlank = typeof newValue !== 'string' || newValue === '';
if (isBlank) {
throw new Error('thingToDo is a required property and cannot be empty')
};
// don't allow `thingToDo` to be a string with a length of 1
const has2chars = typeof newValue === 'string' && newValue.length >= 2;
if (!has2chars) {
throw new Error('thingToDo must have a length of more than 1 character')
};
}
}
また、設定メソッド内で検証を行うこともできます。get() / set()メソッドを、装飾付きのアイテムと組み合わせて使用する方法について読んでみましょう。
@Prop() Options
@Prop()デコレータには、コンポーネント上のpropの動作を変更するためのオプション引数が用意されています。
@Prop()のオプション引数は、以下のフィールドを1つ以上含むオブジェクトです。
export interface PropOptions {
attribute?: string;
mutable?: boolean;
reflect?: boolean;
}
Attribute Name (attribute)
プロパティとコンポーネントの属性は密接に関連していますが、必ずしも同じものではありません。属性とは、…です。 HTMLの概念や性質は、オブジェクト指向プログラミングに固有の JavaScriptの概念です。
Stencilでは、プロパティに対して適用される @Prop()デコレータが、Stencilコンパイラにも同様の処理を指示します。
DOM属性の変更点です。
通常、プロパティの名前はその属性の名前と同じですが、必ずしもそうとは限りません。以下のコンポーネントを 例に取りましょう。
import { Component, Prop, h } from '@stencil/core';
// `MyHttpService` is an `Object` in this example
import { MyHttpService } from '../some/local/directory/MyHttpService';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
@Prop() isComplete: boolean;
@Prop() thingToDo: string;
@Prop() httpService: MyHttpService;
}
このコンポーネントには3つのプロパティがありますが、コンパイラはわずか2つの属性を生成します。それは is-completeと…
thing-to-do.
<todo-list-item is-complete="false" thing-to-do="Read Attribute Naming Section of Stencil Docs"></todo-list-item>
注意すべき点は、httpServiceタイプはプリミティブなタイプではないということです。つまり、number、boolean、またはstringとは異なります。また、DOM属性は
文字列としてのみ扱われるため、"http-service"という名前の関連するDOM属性を持つことは意味がありません。
Stencilは、HTMLで記述されたオブジェクト型の文字列を JavaScriptのオブジェクトとしてシリアル化しようとはしません。
httpServiceの設定方法については、オブジェクト型の propsを参考にしてください。
同時に、isCompleteおよびthingToDoのプロパティは「camelCase」という名前になりますが、属性自体は
case-insensitiveです。そのため、属性の名前はデフォルトでis-completeおよびthing-to-doになります。
幸いなことに、この「デフォルト」の動作は、@Prop()デコレータの attributeオプションを使って変更することができます。
import { Component, Prop, h } from '@stencil/core';
// `MyHttpService` is an `Object` in this example
import { MyHttpService } from '../some/local/directory/MyHttpService';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
@Prop({ attribute: 'complete' }) isComplete: boolean;
@Prop({ attribute: 'thing' }) thingToDo: string;
@Prop({ attribute: 'my-service' }) httpService: MyHttpService;
}
このオプションを使用することで、どのプロパティが DOM属性を持ち、その属性の名前が何であるかを明確にすることができます。 HTMLでこのコンポーネントを使用する際の方法です。
<todo-list-item complete="false" thing="Read Attribute Naming Section of Stencil Docs" my-service="{}"></todo-list-item>
Prop Mutability (mutable)
デフォルトでは、コンポーネント内部から prop の値を変更することはできません。 しかし、以下の例のように、コンポーネント内でプロパティを可変として宣言することで、プロパティが変異することを明示的に許可することができます。
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
@Prop({ mutable: true }) thingToDo: string;
componentDidLoad() {
this.thingToDo = 'Ah! A new value!';
}
}
変更可能な配列とオブジェクト
Stencilは、コンポーネントを効率的に再レンダリングするために、プロパティを参照によって比較します。
オブジェクトや配列の Prop に mutable: true を指定すると、コンポーネント内で Prop の 参照 を変更し、再レンダリングを起こせます。
既存のオブジェクトや配列に変更を加えても、レンダリングを引き起こすことはありません。
例えば、Propという配列を更新する場合です。
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'my-component',
})
export class MyComponent {
@Prop({mutable: true}) contents: string[] = [];
timer: NodeJS.Timer;
connectedCallback() {
this.timer = setTimeout(() => {
// this does not create a new array. when stencil
// attempts to see if any of its Props have changed,
// it sees the reference to its `contents` Prop is
// the same, and will not trigger a render
// this.contents.push('Stencil')
// this does create a new array, and therefore a
// new reference to the Prop. Stencil will pick up
// this change and rerender
this.contents = [...this.contents, 'Stencil'];
// after 3 seconds, the component will re-render due
// to the reference change in `this.contents`
}, 3000);
}
disconnectedCallback() {
if (this.timer) {
clearTimeout(this.timer);
}
}
render() {
return <div>Hello, World! I'm {this.contents[0]}</div>;
}
}
上の例では、this.contents.push('Stencil')を使用してPropをその場で更新しても、何の効果もありません。
Stencil は Prop の 参照 を比較します。this.contents の参照は変わらないため、変更を検出できません。
これは、性能の向上のために行われているものです。
もし、Stencilが配列内の各スロットを順番にチェックして、変化があったかどうかを判断しなければならない場合、性能が低下することになります。
むしろ、パフォーマンスの観点から、また、より自然な表現として、Propを再割り当てる方が良いとされています(上記の例では、スプレッド演算子を使用しています)。
物体についても同様です。 既存のオブジェクトを直接更新する代わりに、スプレッド構文で新しいオブジェクトを作成します。参照が変わるため、再レンダリングが発生します。
import { Component, Prop, h } from '@stencil/core';
export type MyContents = {name: string};
@Component({
tag: 'my-component',
})
export class MyComponent {
@Prop({mutable: true}) contents: MyContents;
timer: NodeJS.Timer;
connectedCallback() {
this.timer = setTimeout(() => {
// this does not create a new object. when stencil
// attempts to see if any of its Props have changed,
// it sees the reference to its `contents` Prop is
// the same, and will not trigger a render
// this.contents.name = 'Stencil';
// this does create a new object, and therefore a
// new reference to the Prop. Stencil will pick up
// this change and rerender
this.contents = {...this.contents, name: 'Stencil'};
// after 3 seconds, the component will re-render due
// to the reference change in `this.contents`
}, 3000);
}
disconnectedCallback() {
if (this.timer) {
clearTimeout(this.timer);
}
}
render() {
return <div>Hello, World! I'm {this.contents.name}</div>;
}
}
Reflect Properties Values to Attributes (reflect)
場合によっては、Propを特定の属性と同期させることが有効になることがあります。その場合は、reflectオプションを設定することができます。
@Prop()のデコレータを trueに移動すると、プロップが反射される際、そのプロップは DOMでは HTMLの属性として表現されます。
以下のコンポーネントを例に取りましょう:
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'todo-list-item',
})
export class ToDoListItem {
@Prop({ reflect: false }) isComplete: boolean = false;
@Prop({ reflect: true }) timesCompletedInPast: number = 2;
@Prop({ reflect: true }) thingToDo: string = "Read Reflect Section of Stencil Docs";
}
上記の例で使用されているコンポーネントは default valuesを使用しています。したがって、HTMLでも同様に使用することができます。
<!-- Example of using todo-list-item in HTML -->
<todo-list-item></todo-list-item>
DOMで表示 される際、reflect: trueで設定されたプロパティは、DOMにも反映されます。
<todo-list-item times-completed-in-past="2" thing-to-do="Read Reflect Section of Stencil Docs" ></todo-list-item>
「reflect」というプロパティが設定されていない場合、例えばisCompleteのような値は、属性として表示されません。しかし、それはその値が存在しないと
いう意味ではありません。つまり、isCompleteというプロパティには、依然としてfalseという値が含まれているのです。
const cmp = document.querySelector('todo-list-item');
console.log(cmp.isComplete); // it prints 'false'
Prop Getters and Setters
@Propで装飾されたメンバーを、get()や set()の方法で使用することもできます。これは、検証に役立ちます。
(@Watchデコレーターの使用に代わる方法として)、入力データを変換したり、読み取り専用のプロパティを公開したりすることができる。
import { Component, Prop, h } from '@stencil/core';
@Component({
tag: 'get-set-props',
})
export class GetSetProps {
// A read-only prop
private internalValue = 'should not change';
@Prop()
get readOnlyProp () { return this.internalValue; }
// A validated prop
private safeValue: 'this' | 'or maybe this' = 'this';
@Prop()
get validatedProp () {
return this.safeValue;
}
set validatedProp (incomingDodgyValue: any) {
if (['this', 'or maybe this'].includes(incomingDodgyValue)) {
this.safeValue = incomingDodgyValue;
}
}
private dateValue: Date = new Date();
// A transformed prop
@Prop()
get transformedProp () {
return this.dateValue;
}
set transformedProp (incomingStringVal: string) {
this.dateValue = new Date(Date.parse(incomingStringVal));
}
}
タイプやオプションに関するほとんどのドキュメントは、@Propを取得したり設定したりする場合にも同様に適用されます。
ただし、変わりやすいについては、そのような処理を行うことは理にかなっていないため、適用されません。