【React 17.0.2】属性(props)と状態(state)

Reactコンポーネントでも親子関係を持つと考えられる

1
2
3
4
5
6
<Parent>
    <ChildOne />
    <ChildTwo>
        <Baby />
    </ChildTwo>
</Parent>

props: 親から子へ渡される属性値 ※子コンポーネントで変更できない
state: 子の内部状態 ※親コンポーネントから参照・変更できない
L stateが更新されるとstateを持つコンポーネントが再レンダリングされる

### props
外部から渡される属性値は、propsと呼ぶ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<Component
    string="this is string"
    number={123}
    bool={true}
    array={[9,8,7]}
    object={{ hello: 'world'}}
    func = {a=> a*2}
    variable={something}
/>
 
<button
    id="the-button"
    className="button is-primary"
    onClick={handleClick}
>Button</button>
<label htmlFor="the-id">Label</label>
 
<input
    type="text"
    id="email"
    arial-labelledby="the-label"
    aria-required="true"
/>

### イベント処理
イベントの処理は別に書く

1
2
3
4
5
const handleClick = () => {
     
}
 
const button = <button onClick={handleClick}>Click me</button>;

### カスタム属性
独自要素には自由にpropsを定義できる

1
2
3
4
5
6
7
8
<Component customProp={something} />
<Layout
    header={<Header />}
    content={<Content />}
    footer={<Footer />}
/>
 
<Panel narrow>...</Panel>

### state
コンポーネント内部でデータを管理したい場合は、useState関数(state)を使う
  L useStateは更新されたデータを覚えていて、2回目以降はそちらを使う

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function CountButton(){
    const countState = React.useState(0);
 
    const count = countState[0]; // 状態
    const setCount = countState[1]; // 状態を更新するための関数
 
    const handleClick = () => setCount(count + 1);
 
    return <button onClick={handleClick}>{count}</button>;
}
 
const root = document.getElementById('root');
 
 
ReactDOM.render(<CountButton />, root);

stateによる更新の影響範囲を確認

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function Parent(){
    const [num, setNum] = React.useState(0);
 
    const handleClick = () => setNum(num + 1);
 
    return(
        <>
            <p><button onClick={handleClick}>{num}</button></p>
            <p><Child num={num} /></p>
            <p><Child num={num} /></p>
        </>
    );
}
 
function Child({ num }){
    const [myNum, setMyNum] = React.useState(0);
 
    const handleClick = () => setMyNum(myNum + 1);
 
    return (
        <button className="child" onClick={handleClick}>
            {num + myNum}
        </button>
    );
}

### フック
フックはReactの便利な機能を導入できるヘルパー関数
useStateはフックの一つ

なるほど、propsだけでなくuseStateを使って開発していくのね。
なんとなくイメージが沸きました。