メインコンテンツまでスキップ
バージョン: v5 (Preview)

JSXの使用

Stencilコンポーネントは、一般的な宣言型テンプレート構文であるJSXを使用してレンダリングされます。 各コンポーネントには、実行時にDOMにレンダリングされるコンポーネントのツリーを返す render関数があります。

By default, Stencil sets up projects for JSX automatically. If you're setting up a project manually, add the following to your tsconfig.json:

tsconfig.json
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "@stencil/core"
}
}

基本​

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>コンポーネントを取得します。

Click both counters a few times, then Toggle. The counter without a key keeps its count, and the one with a key starts again from its initialValue:

my-counter.tsx
import { Component, Prop, State } from '@stencil/core';

@Component({ tag: 'my-counter' })
export class MyCounter {
@Prop() initialValue = 0;
@State() count = 0;

componentWillLoad() {
this.count = this.initialValue;
}

render() {
return <button onClick={() => this.count++}>Count: {this.count}</button>;
}
}
my-toggle-demo.tsx
import { Component, State } from '@stencil/core';

@Component({ tag: 'my-toggle-demo' })
export class MyToggleDemo {
@State() someCondition = true;

render() {
return (
<div>
<button onClick={() => (this.someCondition = !this.someCondition)}>Toggle</button>
<p>
Without key:{' '}
{this.someCondition
? <my-counter initialValue={2} />
: <my-counter initialValue={5} />
}
</p>
<p>
With key:{' '}
{this.someCondition
? <my-counter key="a" initialValue={2} />
: <my-counter key="b" initialValue={5} />
}
</p>
</div>
);
}
}
index.html
<script type="module" src="./my-counter.js"></script>
<script type="module" src="./my-toggle-demo.js"></script>

<my-toggle-demo></my-toggle-demo>

スロット​

A <slot> in your JSX marks where content passed into the component goes. See Slots for named slots, fallback content, and how slots work with and without shadow DOM.

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>{ this.todos[0].taskName }</span>
<span>{ this.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, wrap them in a fragment, <>...</>, which groups elements without adding a wrapper node to the DOM. No commas are needed:

render() {
return (
<>
<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>
</>
);
}

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)。

Explicitly setting attributes or properties​

By default, Stencil tries to intelligently determine whether to set an attribute or (more commonly) a property on an element when using JSX. However, in some cases you may want to explicitly set one or the other. You can do this by using the attr: or prop: prefixes. For example:

<input attr:value="Hello" />

will set the value attribute on the input element, while:

<input prop:value="Hello" />

will explicitly set the value property on the input element.

For an input's value, the difference shows once someone has typed. Type in both inputs, then click Toggle. The prop:value input shows the new value. The attr:value input keeps what you typed, because the attribute is only the input's default value:

my-cmp.tsx
import { Component, State } from '@stencil/core';

@Component({ tag: 'my-cmp' })
export class MyCmp {
@State() greeting = 'Hello';

private toggle = () => {
this.greeting = this.greeting === 'Hello' ? 'Goodbye' : 'Hello';
};

render() {
return (
<div>
<input attr:value={this.greeting} />
<input prop:value={this.greeting} />
<button onClick={this.toggle}>Toggle</button>
</div>
);
}
}

共有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>
);
}
}

その他のリソース​