개발의변화
DOM에 이름 달기,컴포넌트 반복 본문
DOM 요소에 어떤 작업 해야 할 때 css에서 특정 id에 특정 스타일을 적용하거나 해당 id를 가진 요소를 찾아서 작업할 수 있다.
ref는 DOM을 꼭 직접적으로 건드릴 때 만들 수 있다.
ref 사용하려면 HOOKS 사용해야 한다.
리액트에서 이런 작업은 굳이 DOM에 접근하지 않아도 state로 구현 할 수 있다.
꼭 DOM을 사용해야 하는 상황
특정 input에 포커스 주기
스크롤 박스 조작하기
Canvas 요소에 그림 그리기
ref 사용
콜백 함수를 사용하는 것 , ref를 달고자 하는 요소에 ref라는 콜백 함수로 props로 전달해 주면 된다. 이 콜백 함수는 ref 사용
arr.map(callback, [thisArg])
callback: 새로운 배열의 요소를 생성하는 함수로 파라미터는 다음 세 가지입니다.
currentValue: 현재 처리하는 요소
index: 현재 처리하고 있는 요소의 index 값
array: 현재 처리하고 있는 원본 배열
thisArg: callback 함수 내부에서 사용할 this 레퍼런스
데이터 배열을 컴포넌트 배열로 변환하기
import React from 'react'
const IterationSample = () => {
const names = ['눈사람','얼음','눈','바림']
const nameList = names.map(name => <li>{name}</li>);
return <ul>{nameList}</ul>
};
export default IterationSample;
map을 통해 <li> </li> JSX코드로 된 배열 생성훈 새로 nameList에 담기
key설정
map함수의 인자로 전달되는 함수 내부에서 컴포넌트 props를 설정하듯이 설정
key 값은 유일해야 한다.
map의 두번째 파라미터로 index를 먹이면 된다.
import React from 'react'
const IterationSample = () => {
const names = ['눈사람','얼음','눈','바림']
const nameList = names.map((name,index) => <li key={index}>{name}</li>);
return <ul>{nameList}</ul>
};
export default IterationSample;
데이터 추가기능 구현하기
import React, {useState} from 'react'
const IterationSample = () => {
const [names,setNames] = useState([
{id: 1, text: '눈사람'},
{id: 2, text: '배고파'}
])
const [inputText, setInputText] = useState('');
const [nextId, setNextId] = useState(5);
const onChange = e => setInputText(e.target.value)
const onClick = () => {
const nextNames = names.concat({
id: nextId,
text:inputText
});
setNextId(nextId+1)
setNames(nextNames)
setInputText('');
}
const namesList = names.map(name => <li key= {name.id}>{name.text}</li>)
return <>
<input value={inputText} onChange={onChange}/>
<button>추가</button>
<ul>{namesList}</ul>
</>
};
export default IterationSample;
onClick 이벤트 설정
concat을 통해 새로운 항목을 추가 배열
filter를 통해 데이터 제거
const onRemove = id => {
const nextNames = names.filter(name => name.id !== id);
setNames(nextNames);
};