はじめに
react入門いたしました。
reactの基礎である、props、stateについて
カウントアップアプリを通じて学びました。
Props
- 親コンポーネントから子コンポーネントに値を渡す方法
- データの属性によって記述の仕方が違います、文字列は""で囲む、数字は{}で囲む
- 子コンポーネントは引数として受け取る。受けつる際に{}で囲む
親コンポーネント
const App = () => {
return (
<>
<section style={{ paddingTop: "50px" }}>
<h1 className="ui container">カウントアプリ</h1>
<div className="ui container" style={{ display: "flex" }}>
<CountButton text="+1" num={1} />
<CountButton text="+2" num={2} />
<CountButton text="+3" num={3} />
<CountButton text="+4" num={4} />
<CountButton text="+5" num={5} />
</div>
</section>
</>
);
};
text、numという変数で値を子コンポーネントに渡しております。
子コンポーネント
const CountButton = (props) => {
const [num, setNum] = useState(0);
const onCountUp = () => {
setNum(num + props.num);
};
return (
<>
<div className="count_box" style={{ marginRight: "20px" }}>
<p style={{ fontSize: "20px" }}>
Count<span style={{ fontSize: "24px" }}>{num}</span>
</p>
<button
className="ui button blue"
style={{ width: "100%" }}
onClick={onCountUp}
>
{props.text}
</button>
</div>
</>
);
};
子コンポーネントでは引数で(props)の値を受け取る
{}で囲んでprops.変数名で値を表示する
State
- 各コンポーネントが持つ状態
- Stateが変更されると再レンダリングされる。
- 条件によって状態が変わる部分をStateで管理する
import React, { useState } from "react";
const CountButton = (props) => {
const [num, setNum] = useState(0);
const onCountUp = () => {
setNum(num + props.num);
};
return (
<>
<div className="count_box" style={{ marginRight: "20px" }}>
<p style={{ fontSize: "20px" }}>
Count<span style={{ fontSize: "24px" }}>{num}</span>
</p>
<button
className="ui button blue"
style={{ width: "100%" }}
onClick={onCountUp}
>
{props.text}
</button>
</div>
</>
);
};
まずはuseStateをimportする
const [num, setNum] = useState(0);
一つ目いにStateとして使う変数名(num)、二つ目にそのStateを変更するための関数名(setNum)
useState(初期値)今回は0です。
setNum(num + props.num);
Stateを更新する、numにprposの値分プラスする