2023.02.06
State란 컴포넌트 내부에서 바뀔 수 있는 값을 의미한다. 바꿔야 하는 이유는 UI(엘리먼트)로의 반영을 위해서 이다.
State를 만들 때는 useState()를 사용한다.
import React, { useState } from 'react';
function GrandFather() {
const [name, setName] = useState("김할아"); // 이것이 state!
return <Mother grandFatherName={name} />;
}
// .. 중략
const [ value, setValue ] = useState( 초기값 )
먼저 const 로 선언을 하고 [ ] 빈 배열 을 생성하고, 배열의 첫번째 자리에는 이 state의 이름, 그리고 두번째 자리에는 set 을 붙이고 state의 이름을 붙인다. 그리고 useState( ) 의 인자에는 이 state의 원하는 처음값 을 넣어준다.
// src/App.js
import React, { useState } from "react";
function Child(props) {
return <div>{props.grandFatherName}</div>;
}
function Mother(props) {
return <Child grandFatherName={props.grandFatherName} />;
}
function GrandFather() {
const [name, setName] = useState("김할아"); // state를 생성
return <Mother grandFatherName={name} />;
}
function App() {
return <GrandFather />;
}
export default App;
setName 을 통해 이름을 바꿀 수 있다. “박할아"로 바꾸고 싶으니 setName(”박할아”) 를 하면 이름이 바뀔 것 이다. 예제는 우리에게 버튼이 있고, 그 버튼을 눌렀을 때 setName("박할아") 를 실행하도록 한다.
// src/App.js
import React, { useState } from "react";
function Child(props) {
return (
<div>
<button
onClick={() => {
props.setName("박할아");
}}
>
할아버지 이름 바꾸기
</button>
<div>{props.grandFatherName}</div>
</div>
);
}
function Mother(props) {
return (
<Child grandFatherName={props.grandFatherName} setName={props.setName} />
);
}
function GrandFather() {
const [name, setName] = useState("김할아");
return <Mother grandFatherName={name} setName={setName} />;
}
function App() {
return <GrandFather />;
}
export default App;
import React from "react";
function App() {
// 버튼을 눌렀을 때 하고 싶은 행동
function onClickHandler() {
console.log("hello button");
}
return (
<div>
<button onClick={onClickHandler}>버튼</button>
</div>
);
}
export default App;
import React, { useState } from "react";
function App() {
const [name, setName] = useState("길동이");
function onClickHandler() {
setName("누렁이");
}
return (
<div>
{name}
<button onClick={onClickHandler}>버튼</button>
</div>
);
}
export default App;
import React, { useState } from "react";
const App = () => {
const [value, setValue] = useState("");
return (
<div>
<input type="text" />
</div>
);
};
export default App;
import React, { useState } from "react";
const App = () => {
const [value, setValue] = useState("");
const onChangeHandler = (event) => {
const inputValue = event.target.value;
setValue(inputValue);
};
console.log(value) // value가 어떻게 변하는지 한번 콘솔찍어보자
return (
<div>
<input type="text" onChange={onChangeHandler} value={value} />
</div>
);
};
export default App;
이벤트 핸들러 안에서 자바스크립트의 event 객체를 꺼내 사용할 수 있다. 즉, 사용자가 입력한 input의 값은 event.target.value 로 꺼내 사용할 수 있다.
마지막으로 state인 value를 input의 attribute인 value에 넣어주면 input과 state 연결이 완료된다.