[React] useState 이용한 input 값 입력 및 출력

소영·2022년 10월 31일
0
const Main = () => {
	const [ text, setText ] = useState('');
    const [ content, setContent ] = useState('');
    
    const onChangeEvent = (e) => {
    	setText(e.target.value);
    }
    
    const onClickEvent = () => {
    	setContent(text);
        
        setText('');
    }
    
    return (
    	<div>
        	<input onChange={ onChangeEvent } value={ text } />
            <button onClick={ onClickEvent }>설정</button>
            <p>값: { content }</b>
        </div>
	)
}

localStorage를 이용한 input 값 저장 후 출력
(페이지 나갔다가 다시 들어왔을 때나 새로고침을 해도 데이터가 그대로 남아있음)

const Main = () => {
	const [ text, setText ] = useState('');
    
    const onChangeEvent = (e) => {
    	setText(e.target.value);
    }
    
    const onClickEvent = () => {
    	localStorage.setItem('contents', text);	// 자료 저장 (key : value)
        
        setText('');
    }
    
    return (
    	<div>
        	<input onChange={ onChangeEvent } value={ text } />
            <button onClick={ onClickEvent }>설정</button>
            <p>값: { localStorage.getItem('contents') }</b>	
            // localStorage에 있는 자료 출력
        </div>
	)
}

0개의 댓글