LoginSignup
0
0

More than 1 year has passed since last update.

Controlled ComponentとUncontrolled Component

Posted at

Controlled Component

Controlled Component:FormのElementをstateにて管理すること。(=Reactにより、管理される)
import React from 'react'
import { useState } from 'react';

export default function ControlledComponent() {
    // stateを定義する。引数は初期値を定義。
    const [name, setName]=  useState('');
    const [essay, setEssay]=  useState('Please write Essay');

    function handleChange(event) {
        // synthetic Eventを受け取る
        setName(event.target.value); // setState(更新する値)
    }

    function handleEssayChange(event) {
        // synthetic Eventを受け取る
        setEssay(event.target.value); // setState(更新する値)
    }
    
    function handleSubmit(event) {
        // synthetic Eventを受け取る
        alert(`name: ${essay}, essay: ${essay}`);
        event.preventDefault(); // prevent to default work(in this case, prevent to reload)
    }
    return (
        <form onSubmit={handleSubmit}>
            <label>
            Name:
            {/* value={stateを定義する} */}
            <input type="text" value={name} onChange={handleChange} />
            </label>
            <label>
              {/* value={stateを定義する} */}
                Essay: <textarea value={essay} onChange={handleEssayChange} />
            </label>
            <input type="submit" value="Submit" />
        </form>
    )
}

Uncontrolled Component

Uncontrolled Component:Controlled ComponentはReactによりformのvalueが管理されますが、そうではない場合(valueが読み取り専用の場合、type="file")はReactがformのvalueが分からないため、refというattributeを使用します。
import React, { userRef } from 'react'

export default function UncontrolledComponent() {
    // fileInputRefはUncontrolledのため、明示的にreferenceであることを定義する。
    const fileInputRef = useRef(null); 
    function handleSubmit(event) {
        event.preventDefault();
        alert(
            `Selected file - ${fileInputRef.current.files[0].name}`
        );
    }
    return (
        <form onSubmit={handleSubmit}>
            <label>Upload file:
            {/* uncontrolled component場合、reactはcomponentの値を参照できません。
            しかし、refをcomponentに付与するとcomponentのvalueがrefに込められます。 */} 
            <input type="file" ref={fileInputRef} /> 
            </label>
            <br />
            <button type="submit">Submit</button>
        </form>
        );
}

0
0
3

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