JSXの使用
Stencilコンポーネントは、一般的な宣言型テンプレート構文であるJSXを使用してレンダリングされます。 各コンポーネントには、実行時にDOMにレンダリングされるコンポーネントのツリーを返す render関数があります。
基本
render関数は、画面に描画されるコンポーネントのツリーを出力するために使用されます。
class MyComponent {
render() {
return (
<div>
<h1>Hello World</h1>
<p>This is JSX!</p>
</div>
);
}
}
この例では、 h1とpの2つの子要素を持つ divのJSX表現を返します。
ホスト要素
コンポーネント自体にクラスや属性を追加するなど、ホスト要素自体を変更する場合は、 <Host>機能コンポーネントを使用します。 詳細を確認するこちら。
データバインディング
多くの場合、コンポーネントは動的データをレンダリングする必要があります。 JSXでこれを行うには、変数の前後に {}を使用します。
render() {
return (
<div>Hello {this.name}</div>
)
}
If you're familiar with ES6 template variables, JSX variables are very similar, just without the $:
//ES6
`Hello ${this.name}`
//JSX
Hello {this.name}
条件付き
異なるコンテンツを条件付きでレンダリングする場合は、JavaScriptのif/elseステートメントを使用できます。
ここで、 nameが定義されていない場合は、別の要素をレンダリングできます。
render() {
if (this.name) {
return ( <div>Hello {this.name}</div> )
} else {
return ( <div>Hello, World</div> )
}
}
さらに、インライン条件は、JavaScriptの三項演算子を使用して作成できます。
render() {
return (
<div>
{this.name
? <p>Hello {this.name}</p>
: <p>Hello World</p>
}
</div>
);
}
注意: Stencilはパフォーマンスを向上させるためにDOM要素を再利用します。 次のコードについて考えてみます。
{someCondition
? <my-counter initialValue={2} />
: <my-counter initialValue={5} />
}
上記のコードは、次のコードとまったく同じように動作します。
<my-counter initialValue={someCondition ? 2 : 5} />
したがって、 someConditionが変更されても、<my-counter>の内部状態はリセットされず、componentWillLoad()などのライフサイクルメソッドは起動しません。 代わりに、条件付きはまったく同じコンポーネントへの更新をトリガーするだけです。
条件付きでコンポーネントを破棄して再作成する場合は、 key属性を割り当てることができます。 これは、コンポーネントが実際には異なる兄弟であることをStencilに通知します。
{someCondition
? <my-counter key="a" initialValue={2} />
: <my-counter key="b" initialValue={5} />
}
このように、 someConditionが変更 された場合、ライフサイクルメソッドcomponentWillLoad()およびcomponentDidLoad() も実行する新しい内部状態を持つ新しい<my-counter>コンポーネントを取得します。
スロット
多くの場合、コンポーネントはコンポーネントツリーの特定の場所に動的な子をレンダリングする必要があります。これにより、開発者はコンポーネントを使用するときに子コンテンツを提供でき、コンポーネントはその子コンポーネントを適切な場所に配置します。
これを行うには、 my-component内でSlotタグを使用できます。
// my-component.tsx
render() {
return (
<div>
<h2>A Component</h2>
<div><slot /></div>
</div>
);
}
次に、ユーザーがコンポーネント my-componentを作成するときに子コンポーネントを渡すと、my-componentはそれを配置します
上記の2番目の <div>内のコンポーネント:
render(){
return(
<my-component>
<p>Child Element</p>
</my-component>
)
}
スロットには、スロットの出力場所を指定できるように「名前」を付けることもできます。
// my-component.tsx
render(){
return [
<slot name="item-start" />,
<h1>Here is my main content</h1>,
<slot name="item-end" />
]
}
render(){
return(
<my-component>
<p slot="item-start">I'll be placed before the h1</p>
<p slot="item-end">I'll be placed after the h1</p>
</my-component>
)
}
Slots Outside Shadow DOM
Slots are native to the Shadow DOM, but Stencil polyfills
the behavior to work for non-shadow components as well. However, you may encounter issues using slots outside the Shadow DOM especially with
component trees mixing shadow and non-shadow components, or when passing a slot through many levels of components. In many cases, this behavior can
be remedied by wrapping the slot in an additional element (like a div or span) so the Stencil runtime can correctly "anchor" the relocated
content in its new location.
There are known use cases that the Stencil runtime is not able to support:
- Forwarding slotted content to another slot with a different name:
It is recommended that slot names stay consistent when slotting content through multiple levels of components. Avoid defining slot tags like<slot name="start" slot="main" />.
Dealing with Children
The children of a node in JSX correspond at runtime to an array of nodes,
whether they are created by mapping across an array with
Array.prototype.map
or simply declared as siblings directly in JSX. This means that at runtime the
children of the two top-level divs below (.todo-one and .todo-two) will be
represented the same way:
render() {
return (
<>
<div class="todo-one">
{this.todos.map((todo) => (
<span>{ todo.taskName }</span>
)}
</div>
<div class="todo-two">
<span>{ todos[0].taskName }</span>
<span>{ todos[1].taskName }</span>
</div>
</>
)
}
If this array of children is dynamic, i.e., if any nodes may be added,
removed, or reordered, then it's a good idea to set a unique key attribute on
each element like so:
render() {
return (
<div>
{this.todos.map((todo) => (
<div key={todo.uid}>
<div>{todo.taskName}</div>
</div>
))}
</div>
)
}
When nodes in a children array are rearranged Stencil makes an effort to
preserve DOM nodes across renders but it isn't able to do so in all cases.
Setting a key attribute lets Stencil ensure it can match up new and old
children across renders and thereby avoid recreating DOM nodes unnecessarily.
Do not use an array index or some other non-unique value as a key. Try to ensure that each child has a key which does not change and which is unique among all its siblings.
Automatic Key Insertion
During compilation Stencil will automatically add key attributes to any JSX nodes in your component's render method which are not nested within curly braces. This allows Stencil’s runtime to accurately reconcile children when their order changes or when a child is conditionally rendered.
For instance, consider a render method looking something like this:
render() {
return (
<div>
{ this.disabled && <div id="no-key">no key!</div> }
<div id="slot-wrapper">
<slot/>
</div>
</div>
);
}
While it might seem like adding a key attribute to the #slot-wrapper div
could help ensure that elements will be matched up correctly when the component
re-renders, this is actually superfluous because Stencil will automatically add
a key to that element when it compiles your component.
The Stencil compiler can only safely perform automatic key insertion in certain scenarios where there is no danger of the keys accidentally causing elements to be considered different when they should be treated the same (or vice versa).
In particular, the compiler will not automatically insert key attributes if a
component's render method has more than one return statement or if it
returns a conditional
expression.
Additionally, the compiler will not add key attributes to any JSX which is
found within curly braces ({ }).
ユーザー入力の処理
StencilはネイティブのDOMイベントを使用します。
ボタンクリックの処理例を次に示します。 矢印関数