HTML2Reactを作ろう

皆さん、とりあえず何か作ろうとHTMLで始めてしまって、後々困ること、ありますよね?
例えばこの前べこが作った トマト鯖 サイトとか
自分自身Reactが一番使い慣れてると思ってるので、とりあえず自動で変換できるツールを作りたいと思います。

1. JS/HTML統合

このシステムでは、まず全てのコードを全てのコンポーネントにまとめます。

<DOCTYPE html>
<html>
<body>
<p>皆さんこんにちは!テストコードだよ!!</p>
<p id="time">00:00:00</p>
<script>
setInterval(() => {
const d = new Date();

const pad = (n) => String(n).padStart(2, '0');

const year = d.getFullYear();
const month = pad(d.getMonth() + 1);
const day = pad(d.getDate());
const hours = pad(d.getHours());
const minutes = pad(d.getMinutes());
const seconds = pad(d.getSeconds());

const formatedDate = `${hours}:${minutes}:${seconds}`;

document.getElementById("time").textContent = formatedDate;
});
</script>
</body>
</html>

これを実現する際、まずは全て以下と同じようにベースコンポーネントを作成します。

function App() {
const [elmentChildren_p_1, setValue_elmentChildren_p_1] = useState<null | string>(null);
const [elmentChildren_p_2, setValue_elmentChildren_p_2] = useState<null | string>(null);

return (
<>
<p>{elmentChildren_p_1 ?? "皆さんこんにちは!テストコードだよ!!"}</p>
<p id="time">{elmentChildren_p_2 ?? "00:00:00"}</p>
</>
);
}

次に、スクリプトを移植していきます。
基本的には変数定義はコンポーネント上のトップレベル、その他はuseEffectに閉じ込めます。
つまり、
function App() {
const [elmentChildren_p_1, setValue_elmentChildren_p_1] = useState<null | string>(null);
const [elmentChildren_p_2, setValue_elmentChildren_p_2] = useState<null | string>(null);
useEffect(() => {
const d = new Date();

const pad = (n) => String(n).padStart(2, ‘0’);

const year = d.getFullYear();
const month = pad(d.getMonth() + 1);
const day = pad(d.getDate());
const hours = pad(d.getHours());
const minutes = pad(d.getMinutes());
const seconds = pad(d.getSeconds());

const formatedDate = ${hours}:${minutes}:${seconds};
setValue_elmentChildren_p_2(formattedDate);
});
return (
<>

{elmentChildren_p_1 ?? "皆さんこんにちは!テストコードだよ!!"}

{elmentChildren_p_2 ?? "00:00:00"}

); } ``` ここで重要なのは、.innerHTML, textContent等は特殊な処理として扱われます。 今回の例では該当する状態に変えます。 本来ならstyle、ほとんどのプロパティをやるべきです。 # 2. コンポーネント分離 Reactの強みはコンポーネント単位の再利用です。なので適切に分離しなければ無駄です。なので分離します。 基本的なルールは、 1. 一つのコンポーネントは20要素未満

というわけでやってみましょう。と言いたいところですが、先ほどのサンプルコードは小さいので20未満ですね。次にまずはProps/Context、分離単位を見てみましょう。

1. スクリプトのコンポーネント分離

2. 共通の祖先を持つ引継ぎ

まずは、

というわけで引継ぎ規則を見てみましょう。