강의 유튜브 주소 :

https://www.youtube.com/watch?v=V3QsSrldHqI&list=PLcqDmjxt30RtqbStQqk-eYMK8N-1SYIFn

 

 


 

전체적은 Example.js의 코드를 하나하나 뜯으면서 Hooks로 변경해보겠다.

const React = require('react');
const { Component } = React;

class Example extends Component{
	state = {
    	value : ''
    }
    
    onSubmit = () => {
    	// ...
    };
    
    onChange = () => {
    	// ...
    };
    
    inputEl;
    
    onRefInput = (c) => {
    	this.inputEl = c;
    };
    
    render(){
    	return(
        	<>
            	<form>
                	<input type="text" ref={this.onRefInput} value={this.state.value} onChange={this.onChange}/>
                </form>
            	<div>{this.state.value}</div>
            </>
        );
    }
}    

module.exports = Example

 

require를 import로 수정하고(이건 Hooks와 상관은 없다. 모듈 가져오는 방식)

import React, { Component } from 'react';

// ....

export default Example;

 

class 선언하던 부분, Component도 필요없어졌다.

import React from 'react';

const Example = () => {

};    

export default Example;

 

state부분을 useState를 사용하는 방식으로 수정하고 import해오는 부분을 수정해준다.

// useState 추가
import React, { useState } from 'react';

const Example = () => {

	// state 선언
	const [value, setValue] = useState('');
    
    //....
};    

export default Example;

 

사용하거나 셋팅할때는 아래와 같이 한다.

import React, { useState } from 'react';

const Example = () => {
	const [value, setValue] = useState('');
	
    // setValue를 사용해서 세팅
    const changeValue = (e) => {
    	setValue(e.target.value);
    };
    
    // render가 없어도된다.
    return(
    	<>
       		// this없이 사용가능
			<div>{value}</div>        
        </>
    );
};    

export default Example;

 

ref 까지 수정

// useRef를 추가로 import 해온다.
import React, { useState, useRef } from 'react';

const Example = () => {
	const [value, setValue] = useState('');
    
    // null 초기 값 설정
	const inputEl = useRef(null);
    
    const changeValue = (e) => {
    	setValue(e.target.value);
    };
    
    // focus 접근할때 꼭 current를 잡아준다.
    inputEl.current.focus();
    
    return(
    	<>	
        	<form>
				<input type="text" ref={inputEl} />            
            </form>
			<div>{value}</div>        
        </>
    );
};    

export defualt Example;

 

여기서 수정하다보면 컴파일러가 html과 jsx를 혼동할 수 있다.

class -> className

input의 for -> htmlFor 등의 예약어로 대체해줘야한다.

 

 

 

+ Recent posts