JSXの使用
Stencilコンポーネントは、一般的な宣言型テンプレート構文であるJSXを使用してレンダリングされます。 各コンポーネントには、実行時にDOMにレンダリングされるコンポーネントのツリーを返す render関数があります。
基本
The h and Fragment functions
The h function (short for "hyperscript") is a factory function that creates virtual DOM elements. When you write JSX like <div>Hello</div>, it gets transformed into function calls like h('div', null, 'Hello'). The Fragment function is used to group a list of children without adding extra nodes to the DOM.
Set up in Stencil
Within your Stencil project, make sure to add or modify your tsconfig.json file, adding:
{
"compilerOptions": {
"jsx": "react",
"jsxFactory": "h",
"jsxFragmentFactory": "Fragment"
}
}
You will then need to import h (and Fragment if you plan to use it) from @stencil/core at the top of your component file:
import { h, Fragment, Component } from '@stencil/core';
@Component({
tag: 'my-component',
})
class MyComponent { ... }
(Read more about using the Fragment component in the Complex Template Content section below.)
jsxImportSource alternative
jsxImportSource is a more modern approach that automatically imports the necessary JSX runtime functions instead of manually importing h; the compiler automatically imports what it needs from the specified package.
Set up in Stencil
To use jsxImportSource, modify your tsconfig.json file as follows:
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "@stencil/core"
}
}
Using this approach means you do not need to manually import h or Fragment in your component files.
The render function
The render function is used within your component to output a tree of elements that will be drawn to the screen.
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イベントを使用します。
ボタンクリックの処理例を次に示します。 矢印関数の使用に注意してください。
...
export class MyComponent {
private handleClick = () => {
alert('Received the button click!');
}
render() {
return (
<button onClick={this.handleClick}>Click Me!</button>
);
}
}
入力 changeをリッスンする別の例を次に示します。 矢印関数の使用に注意してください。
...
export class MyComponent {
private inputChanged = (event: Event) => {
console.log('input changed: ', (event.target as HTMLInputElement).value);
}
render() {
return (
<input onChange={this.inputChanged}/>
);
}
}
複雑なテンプレートコンテンツ
これまで、単一のルート要素のみを返す方法の例を見てきました。 ルート要素内に要素をネストすることもできます
コンポーネントに複数の「トップレベル」要素がある場合、 render関数は配列を返すことができます。
<div>要素の間のコンマに注意してください。
render() {
return ([
// first top level element
<div class="container">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>,
// second top level element, note the , above
<div class="another-container">
... more html content ...
</div>
]);
}
Alternatively you can use the Fragment functional component, in which case you won't need to add commas:
import { Fragment } from '@stencil/core';
...
render() {
return (<Fragment>
// first top level element
<div class="container">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
<div class="another-container">
... more html content ...
</div>
</Fragment>);
}
It is also possible to use innerHTML to inline content straight into an element. This can be helpful when, for example, loading an svg dynamically and then wanting to render that inside of a div. This works just like it does in normal HTML:
<div innerHTML={svgContent}></div>
DOM要素への参照を取得する
通常の document.querySelectorで行うように、要素への直接参照を取得する必要がある場合は、JSXでrefを使用することをお勧めします。 フォームで refを使用する例を見てみましょう。
@Component({
tag: 'app-home',
})
export class AppHome {
textInput!: HTMLInputElement;
handleSubmit = (event: Event) => {
event.preventDefault();
console.log(this.textInput.value);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={(el) => this.textInput = el as HTMLInputElement} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
この例では、refを使用して、入力ref = {(el)=> this.textInput = el asHTMLInputElement}への参照を取得しています。 次に、その参照を使用して、テキスト入力から直接値を取得するなどの操作を行うことができます(this.textInput.value)。
共有JSXノードを避ける
レンダラーは、パフォーマンスを向上させるために要素ルックアップをキャッシュします。 ただし、これによる副作用として、まったく同じJSXノードを同じレンダラー内で共有しないでください。
以下の例では、 sharedNode変数はrender()関数内で複数回再利用されています。 レンダラーは、参照をキャッシュすることでDOM要素のルックアップを最適化できますが、これにより、ノードが再利用されるときに問題が発生します。 代わりに、以下の変更された例のように、常に一意のノードを生成することをお勧めします。
@Component({
tag: 'my-cmp',
})
export class MyCmp {
render() {
- const sharedNode = <div>Text</div>;
return (
<div>
- {sharedNode}
- {sharedNode}
+ <div>Text</div>
+ <div>Text</div>
</div>
);
}
}
または、戻り値が一意のインスタンスになるため、代わりに、共通のJSXノードを返すファクトリ関数を作成することもできます。 例えば:
@Component({
tag: 'my-cmp',
})
export class MyCmp {
getText() {
return <div>Text</div>;
}
render() {
return (
<div>
{this.getText()}
{this.getText()}
</div>
);
}
}