key
의 역할true
, false
, null
, undefined
이러한 값들은 화면에 렌더되지 않는다. 이를 {true ? <div></div> : undefined}
이런 식으로 활용할 수 있다.
return (
<>
<div>{[false, null, undefined, true]}</div>
<div>{false}</div>
<div>{null}</div>
<div>{undefined}</div>
<div>{true}</div>
</>
)
key
의 역할key
값을 비교해서 원래 있던 것은 다시 렌더링 하지 않는다.key
는 rops
으로 전달되지 않는다. (props
이름을 key
로 정의하는 것을 피하자! key
는 예약이므로 전달이 안 된다.)key
값이 없어도 사실 동작에는 문제 없지만, 최적화를 위해서 부여하는 것이다. (성능 향상)map()
을 이용해서 1~100까지 버튼을 출력const arr = Array.from(Array(100), (_, i) => {return(i+1)});
function App() {
return (
<div>
{
arr.map((num) => {
if(num % 10 === 0) return null;
if(num % 7 === 0) {
num = "7의 배수"
}
return(<button>{num}</button>)
})
}
</div>
);
}
// key를 줄 경우
const arr = Array.from(Array(100), (_, i) => {return(i+1)});
function App() {
return (
<div>
{
arr.map((num) => {
if(num % 10 === 0) return null
if(num % 7 === 0) {
// num = "7의 배수"
return (<button key={num}>7의 배수</button>)
}
return(<button key={num}>{num}</button>)
})
}
</div>
);
}
onclick
이 아닌 onClick
으로 작성한다.onClick={실행될 함수}
undefined
를 리턴한다.const arr = Array.from(Array(100), (_, i) => {return(i+1)});
const handleClickButton = (num) => () => {
alert(num)
}
function App() {
return (
<div>
{
arr.map((num) => {
return(<button key={num} onClick={handleClickButton(num)} >{num}</button>)
})
}
</div>
);
}
🤔
closure
handleClick
=item1
을 받는 함수 (return
값은item2
를 받는 함수)
바깥에 있는 함수까지 재사용 할 수 있다.
다음 코드에서 App
컴포넌트에는 key
를 추가하고, 하단 이미지와 같은 결과가 출력되도록 Card
컴포넌트를 채워넣자.
import React from 'react';
const users = [{
name: 'kim',
id: 5,
}, {
name: 'hello',
id: 6,
}, {
name: 'jin',
id: 7,
}, {
name: 'hi',
id: 10,
}, {
name: 'yellow',
id: 8,
}];
const Card = (props) => {
return (
<div>
</div>
);
}
const App = () => {
return (
<>
{users.map((user) => <Card user={user} />)}
</>
);
};
export default App;
👉 정답
const Card = (props) => {
return (
<div>
id: {props.user.id}
<br />
name: {props.user.name}
</div>
);
}
const App = () => {
return (
<>
{users.map((user) => <Card user={user} key={user.id} />)}
</>
);
};
👉 오늘 강의의 중요한 결론
key
는 props
로 전달되지 않는다.in Javascirpt