0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】要素とは?

Last updated at Posted at 2023-10-08

本記事ではReactの要素について整理しています。

要素のレンダー

要素とは、Reactアプリケーションの最小単位の構成ブロック。
要素が画面上に表示したいものの説明書き。

最小単位

const element = <h1>Hello,World<h1>

要素とコンポーネントは別の概念。
要素は、コンポーネントを構成するもの。

要素をDOMとして描画する

ルートDOMノード

HTMLファイルに以下のような

要素があるとする。
この中にあるすべてのものが、React DOMによって管理される。
<div id="root"></div>

Reactだけで構築されたアプリケーションは、通常ルートDOMノードを一つだけ持つ。

React要素をルートDOMノードにレンダーする方法

  1. ReactDOM.createRoot()にDOM要素を渡す。
  2. root.render()に React要素を渡す。
const root = ReactDOM.createRoot(
    document.getElementById('root')
);
const element = <h1>Hello, world</h1>
root.render(element)

レンダーされた要素の更新

React要素はイミュータブル。一度要素を作成すると、その小要素もしくは要素を変更することはできない。
要素は映画の中の1つのフレームのようなものであり、それを特定のある時点のUIを表す。

ここまででUIを更新する方法は、新しい要素を作成してroot.render()に渡すことだけ。

const root = ReactDOM.createRoot(
  document.getElementById('root')
);

function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
  root.render(element);
}

setInterval(tick, 1000); // 一定の遅延間隔を置いて関数やコードスニペットを繰り返し呼び出す。

Reactは必要な箇所のみを更新する

React DOMは要素とその子要素を以前のものと比較し、DOMを望ましい状態へと変えるのに必要なだけのDOMの更新を行う

スクリーンショット 2023-10-08 10.17.18(2).png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?